10

When i have several (or even one) selected items and i press simple click on empty space in my ListView (empty space = not row) i want to deselect all my selected items.

This is my deselect all item function:

private void DeselectAllListViewItems()
{
    MyListView.SelectedItems.Clear();
} 

I try to take the selected index with this function:

private void MyListView_MouseDown(object sender, MouseButtonEventArgs e)
{
    if (MyListView.SelectedIndex == -1)
        DeselectAllListViewItems();
}

But in case i have several selected items (or one..) the selected index will never be -1. So how can i distinguish that my mouse click is on empty space and not on item row ?

Verint Verint
  • 557
  • 1
  • 7
  • 19
  • possible duplicate of [How to handle the event when click on empty space?](http://stackoverflow.com/questions/3554425/how-to-handle-the-event-when-click-on-empty-space) – goobering Jun 09 '15 at 16:24
  • Does this answer your question? [WPF Listbox remove selection by clicking on a blank spot](https://stackoverflow.com/questions/23133527/wpf-listbox-remove-selection-by-clicking-on-a-blank-spot) – StayOnTarget May 14 '20 at 15:17

1 Answers1

16

The code below works quite well.

private void MyListView_MouseDown(object sender, MouseButtonEventArgs e)
{
    HitTestResult r = VisualTreeHelper.HitTest(this, e.GetPosition(this));
    if (r.VisualHit.GetType() != typeof(ListBoxItem))
        listView1.UnselectAll();
}

WPF Listbox remove selection by clicking on a blank spot

Community
  • 1
  • 1
J3soon
  • 3,013
  • 2
  • 29
  • 49