无法将 ObservableCollection 绑定到 wpf 中的组合框

本文关键字:组合 wpf ObservableCollection 绑定 | 更新日期: 2023-09-27 18:37:11

我有以下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是包含一个名为ChamberName的属性的对象ObservableCollection,我希望在组合框中显示该属性。

在视图模型中,我有以下代码:

foreach (var chamber in chambers)
{
     Chambers.Add(chamber);
}
OnPropertyChanged(() => Chambers);

但是当此代码执行时,组合框不会更新。我已经使用这种方式进行了很多数据绑定,但我无法让它工作。

有人能看到我在这里做错了什么吗?

无法将 ObservableCollection 绑定到 wpf 中的组合框

您可能需要在文本块上设置相对源,请尝试将文本块的 Text 属性上的绑定修改为以下内容:

{Binding DataContext.ChamberName, RelativeSource={RelativeSource AncestorType=ComboBox}}

正如上面所说,始终检查绑定错误,它们会让您走上正确的道路。

应按如下方式调整属性绑定:

<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}">-->