Wpf 如何将ObservableCollection绑定到组合框?

Wpf 如何将ObservableCollection绑定到组合框?,wpf,vb.net,combobox,observablecollection,vb.net-2010,Wpf,Vb.net,Combobox,Observablecollection,Vb.net 2010,如何在组合框和可观察集合之间获得基本绑定?我只能收到错误消息 VB: XAML: 无论我做什么,组合框似乎总是空的,并且控制台中有一条错误消息: System.Windows.Data错误:40:BindingExpression路径错误:在“对象”“主窗口”(名称=“”)上找不到“单位”属性。BindingExpression:路径=单位;DataItem='MainWindow'(名称='');目标元素是“ComboBox”(Name='ComboBox1');目标属性为“ItemsS

如何在
组合框
可观察集合
之间获得基本绑定?我只能收到错误消息

VB:

XAML:


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

System.Windows.Data错误:40:BindingExpression路径错误:在“对象”“主窗口”(名称=“”)上找不到“单位”属性。BindingExpression:路径=单位;DataItem='MainWindow'(名称='');目标元素是“ComboBox”(Name='ComboBox1');目标属性为“ItemsSource”(类型为“IEnumerable”)


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

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

我完全按照你的建议做了,但仍然收到相同的错误消息,组合框仍然是空的。啊,万岁,真管用!非常感谢。现在,如果我能理解这和我尝试过的几十种变体之间的区别,嘿。@evilspoons是的,它也和C#不同,这就是我被绊倒的原因。显然,在VB中,必须在绑定的XAML元素上显式设置DataContext(在其父元素上的设置不起作用)。
<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 Height="59" HorizontalAlignment="Left" Margin="136,96,0,0" Name="ComboBox1" VerticalAlignment="Top" Width="319" ItemsSource="{Binding}"/>
ComboBox1.DataContext = Units;