【问题标题】:Remove Combobox SelectedItem WPF MVVM删除 Combobox SelectedItem WPF MVVM
【发布时间】:2014-03-18 03:37:11
【问题描述】:

我有一个绑定到 Observable Collection 的组合框,它工作正常。在页面加载时,未设置 Combobox 的选定项目。然后用户可以从组合框中选择一个项目。

但是,我希望能够在单击按钮时取消选择所选项目。有没有办法用 MVVM 模式做到这一点?我真的不想在我的 Observable Collection 的开头插入一个 NULL 项。

到目前为止,我已经通过在视图背后的代码中使用按钮单击事件打破 MVVM 模式来实现这一点...

private void ClearPublicationsButton_Click(object sender, RoutedEventArgs e)
    {
        comboBox1.SelectedItem = null;
    }

谢谢

【问题讨论】:

  • 有一个属性要与 Combobox 的 SelectedItem 绑定。。有一个按钮单击的命令。在按钮单击中,您可能在视图模型中有 Combobox 的集合。在那个,你可以只需通过使用 Combobox 的 SelectedItem 传递属性绑定来删除项目.....

标签: c# wpf mvvm combobox


【解决方案1】:

在视图模型中,它暴露了集合:

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}">

【讨论】:

    猜你喜欢
    • 2012-06-19
    • 2017-02-20
    • 2010-10-14
    • 2011-01-10
    • 2016-09-25
    • 1970-01-01
    • 2015-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多