How to raise / handle the SelectionChanged
event of WPF's ComboBox
using the MVVM pattern?
Explain in detail please I am new to WPF.
What I want, is to do some operations when the ComboBox
item selection changed. How can I achieve it, in an MVVM way?
As first let's make things clear - you can not change event rather you can subscribe to.
Since you've not provided any information regarding where from you want to handle selection changes I will assume most common scenario - handling in the underlying ViewModel. According to MVVM ViewModel should not know anything about View so you can not subscribe directly from ViewModel to the event of a View's control. But you can bind a property of ViewModel to either
SelectedItem
orSelectedIndex
so it would trigger whilst selection changes.There are other solutions doing handling in code behind of a View by accessing a ViewModel via
view.DataContext
but I would suggest avoid such practice, this are work around cases.MVVM solution:
Bind the
ItemsSource
andSelectedItem
properties of theComboBox
to properties in your ViewModel:In MainViewModel.cs:
Code-behind solution:
If you don't want to use MVVM, you can add use this:
And add this in MainWindow.xaml.cs:
I'm a big fan of this method.
Just an enhancement of this solution which exists above, In case you are using Prism Library
(if not, then stop reading now, there is nothing for you)
I really like this solution and I think it is better than any other solution, I just want to make a small enhancement to that solution provided by the Prism Library.
that solution is using
notice the
i:
before theInvokeCommandAction
. It means that theInvokeCommandAction
class exists in thexmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
namespace. This is good and fine, but notice that the Prism library has exactly the same class with the same nameInvokeCommandAction
. It just exists in another namespace, in thexmlns:prism="http://prismlibrary.com/"
namespace.So actually you can replace the following XAML
with this XAML
OK, we can do this, what is the benefit?
To notice the benefit, write the following command in the ViewModel
e parameter is null if you use
<i:InvokeCommandAction>
e parameter is NOT null if you use
<prism:InvokeCommandAction>
Your ViewModel needs to implement INotifyPropertyChanged.
The previously posted XAML is correct: