如何让基本绑定在ComboBox
和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路径错误:'对象'''MainWindow'(Name ='')'上找不到'Units'属性。 BindingExpression:路径=单位; DataItem ='MainWindow'(Name =''); target元素是'ComboBox'(Name ='ComboBox1'); target属性是'ItemsSource'(类型'IEnumerable')
答案 0 :(得分: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;