我有一个绑定到Observable Collection的组合框可以正常工作。在页面加载时,未设置Combobox的选定项目。然后,用户可以从Combobox中选择一个项目。
但是,我希望能够在按钮单击时取消选择所选项目。有没有办法用MVVM模式做到这一点?我真的不想在我的Observable Collection的开头插入一个NULL项。
到目前为止,我已经通过在视图代码后面的按钮单击事件打破MVVM模式来实现这一目标......
private void ClearPublicationsButton_Click(object sender, RoutedEventArgs e)
{
comboBox1.SelectedItem = null;
}
由于
答案 0 :(得分:0)
在视图模型中,它公开了集合:
public MyMasterViewModel()
{
ClearSelectionCommand = new RelayCommand(
() => SelectedNestedViewModel = null,
() => SelectedNestedViewModel != null);
}
public ObservableCollection<MyNestedViewModel> NestedViewModels { /* ... */ }
public MyNestedViewModel SelectedNestedViewModel
{
get { return selectedNestedViewModel; }
set
{
if (selectedNestedViewModel != value)
{
selectedNestedViewModel = value;
OnPropertyChanged("SelectedNestedViewModel");
}
}
}
private MyNestedViewModel selectedNestedViewModel;
public ICommand ClearSelectionCommand { get; private set }
在XAML中:
<Button Command="{Binding ClearSelectionCommand}" Content="Clear selection">
<ComboBox ItemsSource="{Binding NestedViewModels}" SelectedItem="{Binding SelectedNestedViewModel}">