WPF: Cancel a user selection in a databound ListBox?

前端 未结 8 767
独厮守ぢ
独厮守ぢ 2020-12-05 01:02

How do I cancel a user selection in a databound WPF ListBox? The source property is set correctly, but the ListBox selection is out of sync.

I have an MVVM app that

8条回答
  •  独厮守ぢ
    2020-12-05 01:32

    I came up against this recently, and came up with a solution that works well with my MVVM, without the need for and code behind.

    I created a SelectedIndex property in my model and bound the listbox SelectedIndex to it.

    On the View CurrentChanging event, I do my validation, if it fails, I simply use the code

    e.cancel = true;
    
    //UserView is my ICollectionView that's bound to the listbox, that is currently changing
    SelectedIndex = UserView.CurrentPosition;  
    
    //Use whatever similar notification method you use
    NotifyPropertyChanged("SelectedIndex"); 
    

    It seems to work perfectly ATM. There may be edge cases where it doesnt, but for now, it does exactly what I want.

提交回复
热议问题