Selection changed event of combobox in wpf mvvm

2020-02-02 04:16发布

问题:

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?

回答1:

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:

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