Reputation: 4430
I have a ListBox
with SelectionMode="Extended"
. You can only deselect the last item by holding down ctrl while clicking on it. I would like to be able to deselect the item by just clicking on it while not changing the behavior of the Extended
selection mode other than that.
I only found one question about this topic and it actually has a different goal (being able to deselect all items by clicking outside of the ListBox
).
Upvotes: 2
Views: 1367
Reputation: 169240
If I understand your requirement correctly you could handle the PreviewMouseLeftButtonDown
event for the ListBoxItem
container and de-select it if it's already selected:
<ListBox SelectionMode="Extended">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<EventSetter Event="PreviewMouseLeftButtonDown" Handler="OnMouseLeftButtonDown"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBoxItem>1</ListBoxItem>
<ListBoxItem>2</ListBoxItem>
<ListBoxItem>3</ListBoxItem>
</ListBox>
private void OnMouseLeftButtonDown(object sender, MouseEventArgs e)
{
ListBoxItem lbi = sender as ListBoxItem;
if (lbi != null)
{
if (lbi.IsSelected)
{
lbi.IsSelected = false;
e.Handled = true;
}
}
}
This should allow you to be able to de-select an item without using the CTRL
key.
Upvotes: 3