[英]Can't bind ObservableCollection to Combobox in wpf
I have the following xaml: 我有以下xaml:
<UserControl.Resources>
<sivm:Locator x:Key="viewModelLocator" ModelType="{x:Type ViewModels:RateVSConcentrationViewModel}"/>
</UserControl.Resources>
<UserControl.DataContext>
<Binding Path="ViewModel" Source="{StaticResource viewModelLocator}"/>
</UserControl.DataContext>
... ...
<ComboBox Grid.Column="0" Grid.Row="1" Height="20" VerticalAlignment="Top" ItemsSource="{Binding Chambers}" > <!--SelectedItem="{Binding SelectedChamber}">-->
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding ChamberName}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
Chambers
is an ObservableCollection
of objects that contains a property called ChamberName
which I want displayed in the combobox. Chambers
是对象的ObservableCollection
,其中包含一个名为ChamberName
的属性,我希望在组合框中显示该属性。
In the ViewModel I have the following code: 在ViewModel中,我有以下代码:
foreach (var chamber in chambers)
{
Chambers.Add(chamber);
}
OnPropertyChanged(() => Chambers);
But when this code executes the combobox is not updated. 但是,当执行此代码时,组合框不会更新。 I have used this way to do a lot of databinding but I can't get this to work. 我已经使用这种方式进行了很多数据绑定,但是我无法使其正常工作。
Can someone see what I am doing wrong here? 有人可以在这里看到我做错了吗?
You may need to set the relativesource on your textblock, try modifying the binding on the Text property of your textblock to the following: 您可能需要在文本块上设置相对源,尝试将文本块的Text属性上的绑定修改为以下内容:
{Binding DataContext.ChamberName, RelativeSource={RelativeSource AncestorType=ComboBox}}
And as nit said above, always check for binding errors, they will put you on the right path. 正如上面所说的,始终检查绑定错误,它们将使您走上正确的道路。
您应该按如下所示调整属性绑定:
<ComboBox ItemsSource="{Binding Path=ViewModel.Chambers, Source={StaticResource viewModelLocator}}" >
我做到了这一点:
<ComboBox DisplayMemberPath="ChamberName" Grid.Column="0" Grid.Row="1" Height="20" VerticalAlignment="Top" ItemsSource="{Binding Chambers}"> <!--SelectedItem="{Binding SelectedChamber}">-->
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.