Handling Combo Box Selection Change in ViewModel (WPF MVVM)

Windows Presentation Foundation offers various controls and one of the basic control is the combo box.

The combo box has various events such as DropDownOpened, DropDownClosed, SelectionChanged, GotFocus, etc.,.

In this blog, we will see how to handle the selectionchanged event of combo box which is inside grid using Model–View–Viewmodel (MVVM) pattern.

Create Model (Person):

Define a class Person as show below.

Create View Model:

Create a view model named MainWindowViewModel.cs




Create View:

Create a view named MainWindow.xaml.



In the above code, 'Cities' are defined in the view model and are not part of Persons class, the ItemsSource is defined as ItemsSource="{Binding Path=DataContext.Cities,RelativeSource={RelativeSource FindAncestor, AncestorType = UserControl}}" which will take the data from viewmodel Cities property.

We need to import the namespace xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity".

View Code behind:

Create view model field and instantiate the view model in the constructor of View Code behind file.



When we run the application, the grid will bind with the person details and city combo box will be bound with the cities list. Now we can change the city for the respective person and it will be handled by the CityChangeCommand in the view model class.

In this manner we can handle the combo box selection change event using MVVM pattern in WPF.