wpf mvvm 中组合框的选择更改事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21130850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 10:31:57  来源:igfitidea点击:

Selection changed event of combobox in wpf mvvm

wpfmvvm

提问by Jinesh

I am new to wpf and MVVM, and I've spent all day trying to get the value of a ComboBox to my ViewModel on SelectionChanged. I want to call a function in the selection changed process. In mvvm, what is the solution for it?

我是 wpf 和 MVVM 的新手,我花了一整天的时间试图在 SelectionChanged 上将 ComboBox 的值添加到我的 ViewModel。我想在选择更改过程中调用一个函数。在mvvm中,它的解决方案是什么?

回答by Sheridan

In MVVM, we generally don'thandle events, as it is not so good using UI code in view models. Instead of using events such as SelectionChanged, we often use a property to bind to the ComboBox.SelectedItem:

在 MVVM 中,我们通常处理事件,因为在视图模型中使用 UI 代码不太好。SelectionChanged我们经常使用属性来绑定到 ,而不是使用诸如 之类的事件ComboBox.SelectedItem

View model:

查看型号:

public ObservableCollection<SomeType> Items { get; set; } // Implement 
public SomeType Item { get; set; } // INotifyPropertyChanged here

View:

看法:

<ComboBox ItemsSource="{Binding Items}" SelectedItem="{Binding Item}" />

Now whenever the selected item in the ComboBoxis changed, so is the Itemproperty. Of course, you have to ensure that you have set the DataContextof the view to an instance of the view model to make this work. If you want to do something when the selected item is changed, you can do that in the property setter:

现在,每当 中的选定项目ComboBox发生更改时,Item属性也会更改。当然,您必须确保已将DataContext视图的设置为视图模型的实例才能进行此操作。如果您想在所选项目更改时执行某些操作,您可以在属性设置器中执行此操作:

public SomeType Item 
{
    get { return item; }
    set
    {
        if (item != value)
        {
            item = value;
            NotifyPropertyChanged("Item");
            // New item has been selected. Do something here
        }
    }
}