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

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
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)