Open ComboBox from ViewModel in MVVM-scenario

On the Microsoft MSDN-Forums there was a question how to open up a Combobox in an MVVM-scenario from the ViewModel.

To do this, you use the typical MVVM way: You define a bool-Property in the ViewModel to control the DropDown. Here I named it IsDropDownOpen:

public class MainViewModel : ViewModelBase
  private bool isDropDownOpen;

  public bool IsDropDownOpen
    get { return isDropDownOpen; }
      isDropDownOpen = value;

Note that I’m using a ViewModelBase-class in the snippet above. That ViewModelBase-class defines the OnPropertyChanged-method to raise the PropertyChanged-event:

public class ViewModelBase : INotifyPropertyChanged
  protected virtual void OnPropertyChanged([CallerMemberName]string propertyName = null)
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

  public event PropertyChangedEventHandler PropertyChanged;

Now let’s assign the MainViewModel to the MainWindow’s DataContext:

public partial class MainWindow : Window
  public MainWindow()
    DataContext = new MainViewModel();

Now in XAML I can bind the ComboBox’ IsDropDownOpen-Property to the IsDropDownOpen-Property of the MainViewModel that is in the DataContext. In addition I bound a Checkbox to the IsDropDownOpen-Property of the MainViewModel to be able to change the value of that property:

  <CheckBox IsChecked="{Binding IsDropDownOpen,Mode=TwoWay}"/>
  <ComboBox IsDropDownOpen="{Binding IsDropDownOpen,Mode=TwoWay}">
    <ComboBoxItem Content="Item1"/>
    <ComboBoxItem Content="Item2"/>
    <ComboBoxItem Content="Item3"/>

That’s it. When I check the CheckBox, the Dropdown-List opens. Instead of changing the IsDropDownOpen-Property of the MainViewModel with a CheckBox, you could also set the IsDropDownOpen-Property in the MainViewModel when for example a Command is executed.

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *