Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle the SelectionChanged event of ComboBox with MVVM in wpf?

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?

like image 551
Tanya Avatar asked Dec 29 '11 09:12

Tanya


2 Answers

MVVM solution:

Bind the ItemsSource and SelectedItem properties of the ComboBox to properties in your ViewModel:

<ComboBox ItemsSource="{Binding MyItems}" SelectedItem="{Binding MySelectedItem}"/> 

In MainViewModel.cs:

public ObservableCollection<string> MyItems { get; set; }  private string _mySelectedItem; public string MySelectedItem {   get { return _mySelectedItem; }   set   {     // Some logic here     _mySelectedItem = value;   } } 

Code-behind solution:

If you don't want to use MVVM, you can add use this:

 <ComboBox SelectionChanged="ComboBox_SelectionChanged" /> 

And add this in MainWindow.xaml.cs:

private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) {     // Some logic here } 
like image 167
snurre Avatar answered Sep 21 '22 12:09

snurre


I'm a big fan of this method.

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"  <ComboBox Grid.Column="2"  DisplayMemberPath="Data.name" ItemsSource="{Binding Model.Regions}" SelectedItem="{Binding Model.SelectedRegion}">     <i:Interaction.Triggers>         <i:EventTrigger EventName="SelectionChanged">             <i:InvokeCommandAction Command="{Binding RegionChangedCmd}" />         </i:EventTrigger>     </i:Interaction.Triggers> </ComboBox> 
like image 29
Blackey Avatar answered Sep 17 '22 12:09

Blackey