我想显示ComboBoxes
的列表,每个ComboBox
从其父DataContext
获取其主列表,但其值绑定到列出ComboBoxes
的列表}
基本上我有一个项目的主列表(AvailableRegisters
)。然后我显示一个ComboBoxes列表,它基本上等同于当前选择的Register
s
什么有用
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>
答案 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
}
}