无法将ObservableCollection绑定到wpf中的Combobox

时间:2013-10-28 13:58:35

标签: c# wpf xaml data-binding

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

在ViewModel中,我有以下代码:

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

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

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

3 个答案:

答案 0 :(得分:0)

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

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

正如上面提到的,总是检查绑定错误,它们会让你走上正确的道路。

答案 1 :(得分:0)

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

<ComboBox ItemsSource="{Binding Path=ViewModel.Chambers, Source={StaticResource viewModelLocator}}" >

答案 2 :(得分:0)

我做到了这一点:

<ComboBox DisplayMemberPath="ChamberName" Grid.Column="0" Grid.Row="1" Height="20" VerticalAlignment="Top" ItemsSource="{Binding Chambers}"> <!--SelectedItem="{Binding SelectedChamber}">-->