Open ComboBox from ViewModel in MVVM-scenario

Datetime:2016-08-23 01:24:03          Topic: MVVM Model           Share

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; }
    set
    {
      isDropDownOpen = value;
      OnPropertyChanged();
    }
  }
}

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 PropertyChangedEventHandlerPropertyChanged;
}

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

public partialclass MainWindow : Window
{
  public MainWindow()
  {
    InitializeComponent();
    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:

<StackPanel>
  <CheckBoxIsChecked="{Binding IsDropDownOpen,Mode=TwoWay}"/>
  <ComboBoxIsDropDownOpen="{Binding IsDropDownOpen,Mode=TwoWay}">
    <ComboBoxItemContent="Item1"/>
    <ComboBoxItemContent="Item2"/>
    <ComboBoxItemContent="Item3"/>
  </ComboBox>
</StackPanel>

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.





About List