0

我想显示一个列表ComboBoxes,每个ComboBox都从其父级获取其主列表,DataContext但其值绑定到驱动列表的列表ComboBoxes

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

什么有效

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

什么不起作用

  • 当我从组合框中选择另一个项目时,我没有收到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>
4

1 回答 1

1

问题是您只是ComboBox从 ObservableCollection 中选择一个项目。您不会更改集合本身。

如果需要,请在您的ViewModel被调用对象上创建一个属性,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
    }
}

<DataTemplate x:Key="ItemTemplate">
    <ComboBox SelectedItem="{Binding DataContext.SelectedItem, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}" ItemsSource="{Binding DataContext.AvailableRegisters, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}, Mode=TwoWay}">
        <ComboBox.ItemTemplate>
            <DataTemplate><!-- Display it here --></DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>
</DataTemplate>
于 2013-11-01T17:12:24.960 回答