ComboBox绑定 - 接收ComboBox项目更改的通知

时间:2013-11-01 17:07:09

标签: c# silverlight xaml

我想显示ComboBoxes的列表,每个ComboBox从其父DataContext获取其主列表,但其值绑定到列出ComboBoxes的列表}

基本上我有一个项目的主列表(AvailableRegisters)。然后我显示一个ComboBoxes列表,它基本上等同于当前选择的Register s

什么有用

  • 我可以看到每个SelectedRegisters
  • 的正确数量的ComboBox

什么不起作用

  • 当我从组合框中选择另一个项目时,我没有收到CollectionChanged事件

ViewModel代码: 这是我的(缩短的)ViewModel代码

public class DialogViewModel : ViewModelBase
{
    public ObservableCollection<IOViewModel> InputOutputList { get; set; }
    public ObservableCollection<AvailableRegister> AvailableRegisters { get; set; }
}

public class IOViewModel
{
    public ObservableCollection<AvailableRegister> SelectedRegisters { get; set; }

    public IOViewModel()
    {
        this.Registers = new ObservableCollection<AvailableRegister>();
        this.Registers.CollectionChanged += Registers_CollectionChanged;
    }

    void Registers_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        // Never hit when changing combo box
    }
}

XAML

<ItemsControl Grid.Column="4" ItemsSource="{Binding SelectedRegisters, Mode=TwoWay}" ItemTemplate="{StaticResource ItemTemplate}"></ItemsControl>

<DataTemplate x:Key="ItemTemplate">
    <ComboBox SelectedValue="{Binding Path=DataContext, RelativeSource={RelativeSource Self},Mode=TwoWay}" ItemsSource="{Binding DataContext.AvailableRegisters, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}, Mode=TwoWay}">
        <ComboBox.ItemTemplate>
            <DataTemplate><!-- Display it here --></DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>
</DataTemplate>

1 个答案:

答案 0 :(得分:1)

问题是你只是从ObservableCollection的ComboBox中选择一个项目。你不是在改变收藏本身。

如果需要,请在名为ViewModel的{​​{1}}上创建一个属性,然后将SelectedItem绑定到该属性。

SelectedItem

public class IOViewModel
{
    public ObservableCollection<AvailableRegister> SelectedRegisters { get; set; }

    private AvailableRegister _selectedRegister;
    public AvailableRegister SelectedRegister { get { return _selectedRegister; } set { _selectedRegister = value; } }

    public IOViewModel()
    {
        this.Registers = new ObservableCollection<AvailableRegister>();
        this.Registers.CollectionChanged += Registers_CollectionChanged;
    }

    void Registers_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        // Never hit when changing combo box
    }
}