Search code examples
wpfmvvmwpf-controls

Using Button in ComboBox does not make a selection


In the following, the dropdown list of the combobox presents a list of "years" (strings) (the content of the bound "TrialList") along with a button to add another year. It works, the buttons fires the command, but the combobox does not collapse when that happens, which locks up changes made subsequently to the bound list TrialList.

Within MVVM, how can I force a "selection change" when the button is pressed?

<ComboBox>
    <ComboBox.ItemsSource>
        <CompositeCollection>
            <CollectionContainer Collection="{Binding Source={x:Static local:Data.TheAcademicUnit}, Mode=TwoWay, Path=TrialList}"/>
            <ComboBoxItem>
                <Button Content="Add New Year" Command="{Binding ShowNewAcademicYearPanelCommand}"/>
            </ComboBoxItem>
        </CompositeCollection>
    </ComboBox.ItemsSource>
</ComboBox>

Solution

  • You could bind the IsDropDownOpen property of the ComboBox to a source property of the view model that you set to false in the Execute method of the command:

    <ComboBox IsDropDownOpen="{Binding IsOpen}">
    

    View Model:

    private bool _isOpen;
    public bool IsOpen
    {
        get { return _isOpen; }
        set { _isOpen = value; NotifyPropertyChanged(); }
    }
    

    If you want to make a selection when the command is invoked, you should bind to and set the SelectedItem property of the ComboBox the same way.