[英]Remove Combobox SelectedItem WPF MVVM
我有一个绑定到Observable集合的组合框,它工作正常。 在页面加载时,未设置组合框的所选项目。 然后,用户可以从组合框选择一个项目。
但是,我希望能够在单击按钮时取消选择选定的项目。 有什么办法可以通过MVVM模式做到这一点? 我真的不想在Observable Collection的开头插入NULL项。
到目前为止,我已经通过在视图代码后面的按钮单击事件打破了MVVM模式来实现了这一目标...
private void ClearPublicationsButton_Click(object sender, RoutedEventArgs e)
{
comboBox1.SelectedItem = null;
}
谢谢
在视图模型中,它公开了集合:
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}">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.