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

谁说胖子不能爱 提交于 2019-11-29 03:43:43

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/16429392/cant-clear-listbox-selection-using-selecteditem-null-mvvm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!