Reputation: 2216
I want to be able to de-select an item in the ListBox
if the user clicks the same item again. There is the SelectionChanged
event that everyone uses with ListBoxes
, but this obviously will not fire when the selection is unchanged.
There is also no Click
event, something people recommend. Visual Studio C# 2015 does not contain such event.
I have tried using MouseLeftButtonDown
event, but once the ListBox
has been populated with ListBoxItems
, this event does not fire anymore. In addition, I thought about attaching Mouse events to the ListBoxItems
, but this does not seem practicable, as I would have to attach n
number of new events every time I populate the ListBox
.
Does anyone have a XAML solution to this inquiry?
Upvotes: 0
Views: 507
Reputation: 2216
I originally selected mm8's answer, but I later learned that SelectedIndex
is not updated during the PreviewMouseLeftButtonDown
event, a feature I indirectly was asking for in the question. You actually get the previous, out-of-date SelectedIndex
value when using this event.
I found out if you use the MouseLeftButtonUp
event, it actually fires, unlike the MouseLeftButtonDown
event, and I get the most recent value for the SelectedIndex
variable.
For anyone that cares, this is the System.Windows.Controls
's ListBox
version. I tried using the Systems.Windows.Forms
's ListBox
implementation, but it does not support multi-lines out of the box, unlike Controls
, so I threw away that idea.
tldr
Use MouseLeftButtonUp
event.
Upvotes: 0
Reputation: 169150
You could handle the PreviewMouseLeftButtonDown
event for the ListBox
container as I suggested here.
How to disable deselection of items in ListView?
Upvotes: 1