中组合框的选择更改事件

中组合框的选择更改事件

本文介绍了wpf mvvm 中组合框的选择更改事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

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

In MVVM, we generally don't handle 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:

查看模型:

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

查看:

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

现在,只要 ComboBox 中的选定项目发生更改,Item 属性也会更改.当然,您必须确保已将视图的 DataContext 设置为视图模型的实例才能使此工作正常进行.如果你想在选中的项目改变时做一些事情,你可以在属性设置器中做:

Now whenever the selected item in the ComboBox is changed, so is the Item property. Of course, you have to ensure that you have set the DataContext of 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:

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

这篇关于wpf mvvm 中组合框的选择更改事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 07:41