WPF: Cancel a user selection in a databound ListBox?

前端 未结 8 738
独厮守ぢ
独厮守ぢ 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:27

    Bind ListBox's property: IsEnabled="{Binding Path=Valid, Mode=OneWay}" where Valid is the view-model property with the validation algoritm. Other solutions look too far-fetched in my eyes.

    When the disabled appearance is not allowed, a style could help out, but probably the disabled style is ok because changing the selection is not allowed.

    Maybe in .NET version 4.5 INotifyDataErrorInfo helps, I dont'know.

    0 讨论(0)
  • 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.

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