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

后端 未结 1 1711
梦谈多话
梦谈多话 2020-12-29 15:12

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


    &l         


        
相关标签:
1条回答
  • 2020-12-29 16:11

    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.

    0 讨论(0)
提交回复
热议问题