I'm using a WPF ListView to show and select/deselect some items but there are some conditions that user cannot select/deselect an item and I should handle it in the code behind.
I tried to use ListView.SelectionChanged event to handle it but the problem is that when I change the selected item in the code behind (select it again if it was deselected or the other way), the event triggers again and I don't want that.
What is the best way to set conditions on select/deselect ListView item?
I tried to solve it using ListView.PreviewMouseLeftButtonDown event instead of ListView.SelectionChanged. But I wanted to know if there is a better way?
There might be other WPF controls (especially third party ones) that can handle this a little more gracefully. Additionally you can hook into the style of the ListView to alter the mouse-over behavior.
As a crude approach; however, I was able to accomplish what you're looking for by using the
SelectionChangedevent to effectively "undo" any selections we deem invalid.First a simple ListView in xaml:
The
SelectionModebeingSingleis important here as the approach for undoing a selection when multiple items are selected is more complicated.Then, an object to represent our list items with the ToString() overload implemented so we don't have to fiddle with data templates and binding.
This object just represents a string (our data) paired with a boolean of whether or not we want this item to be selectable.
Then, a quick little setup to populate the list with a few item for testing:
And finally, the "magic". The SelectionChanged event handler:
Hopefully the code comments in there make it clear what's going on.