Search code examples
c#wpfmvvmselecteditemselectedvalue

Can't clear ListBox selection using SelectedItem = null - MVVM


I have the following data template (and a corresponding view model, not shown):

<DataTemplate DataType="{x:Type logic:SnapshotListViewModel}">
    <ListBox ItemsSource="{Binding Snapshots}" />
</DataTemplate>

ItemsSource is bound to a list of Snapshots, found inside the viewmodel. My goal is to clear the SelectedItem, so the listbox goes back to its initial, unselected state. The view model implements IPropertyNotified.

I added a binding in the XAML like so:

<ListBox SelectedItem={Binding SelectedSnapshot} .... />

In the view model, I set SelectedSnapshot = null, but nothing happens, even though RaisePropertyChanged was called on the property.

I tried again with SelectedIndex instead of SelectedItem. Still no luck.

I finally found the solution, which I will detail below.


Solution

  • Forget SelectedItem and SelectedIndex. The answer is SelectedValue, along with IsSynchronizedWithCurrentItem="True".

    <ListBox IsSynchronizedWithCurrentItem="True" 
             SelectedValue="{Binding SelectedSnapshotValue}" .../>
    

    Then, when I call ResetSelection() in the view model, SelectedSnapshotValue is set to null,

    void ResetSelection()
    {
        SelectedSnapshotValue = null;
    }
    

    which updates the binding in the data template, using the bound property:

        private SnapshotViewModel selectedSnapshotValue;
        public SnapshotViewModel SelectedSnapshotValue
        {
            get { return selectedSnapshotValue; }
            set
            {
                if (selectedSnapshotValue != value)
                {
                    selectedSnapshotValue = value;
                    RaisePropertyChanged("SelectedSnapshotValue");
                }
            }
        }
    

    This is the only way I was able to get my listbox to reset the selection.