0

如何让基本绑定在 aComboBox和a 之间工作ObservableCollection?除了错误消息,我什么也得不到。

VB:

Class MainWindow
    Dim Units As New ObservableCollection(Of String)

    Private Sub Window_Loaded(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
        Units.Clear()
        Units.Add("in")
        Units.Add("mm")
        Units.Add("cm")
    End Sub
End Class

XAML:

<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
    <ComboBox Height="59" HorizontalAlignment="Left" Margin="136,96,0,0" Name="ComboBox1" VerticalAlignment="Top" Width="319"
              ItemsSource="{Binding Units}"/>
</Grid>

无论我做什么,ComboBox似乎总是空的,并且控制台中有一条错误消息:

System.Windows.Data 错误:40:BindingExpression 路径错误:在 'object' ''MainWindow' (Name='')' 上找不到 'Units' 属性。绑定表达式:路径=单位;数据项='主窗口'(名称='');目标元素是'ComboBox'(名称='ComboBox1');目标属性是“ItemsSource”(类型“IEnumerable”)

4

1 回答 1

2

在 XAML 中,仅更改为 {Binding},或等效地更改为 {Binding Path=.}:

<ComboBox Height="59" HorizontalAlignment="Left" Margin="136,96,0,0" Name="ComboBox1" VerticalAlignment="Top" Width="319" ItemsSource="{Binding}"/>

在 *Window_Loaded* 事件处理程序中,从后面的代码中将数据上下文显式设置为对象:

ComboBox1.DataContext = Units;
于 2012-05-10T23:15:31.780 回答