0
votes

I have a combobox bound to an Observable Collection which works fine. On page load the selected item of the Combobox is not set. The user can then select an item from the Combobox.

However, I want to be able to deselect the selected item on a button click. Is there any way to do this with the MVVM pattern? I don't really want to insert a NULL item at the start of my Observable Collection.

So far I've achieved this by breaking the MVVM pattern with a button click event in the view's code behind...

private void ClearPublicationsButton_Click(object sender, RoutedEventArgs e)
    {
        comboBox1.SelectedItem = null;
    }

Thanks

1
Have a property to Bind with SelectedItem of Combobox.. Have a command for the Button Click.. in the Button Click, you might have the collection of Combobox in your viewmodel.. in that, you can just remove the item by passing the property bind with SelectedItem of Combobox.....Sankarann

1 Answers

0
votes

In view model, which exposes the collection:

public MyMasterViewModel()
{
    ClearSelectionCommand = new RelayCommand(
        () => SelectedNestedViewModel = null, 
        () => SelectedNestedViewModel != null);
}

public ObservableCollection<MyNestedViewModel> NestedViewModels { /* ... */ }

public MyNestedViewModel SelectedNestedViewModel
{
    get { return selectedNestedViewModel; }
    set
    {
        if (selectedNestedViewModel != value)
        {
            selectedNestedViewModel = value;
            OnPropertyChanged("SelectedNestedViewModel");
        }
    }
}
private MyNestedViewModel selectedNestedViewModel;

public ICommand ClearSelectionCommand { get; private set }

In XAML:

<Button Command="{Binding ClearSelectionCommand}" Content="Clear selection">
<ComboBox ItemsSource="{Binding NestedViewModels}" SelectedItem="{Binding SelectedNestedViewModel}">