WPF; 如何在ListView中单击空白区域时取消选择所有选定的项目

Ver*_*int 4 wpf listview

当我有几个(甚至一个)selected items并且我click在我的ListView空空间(简单空格=不是行)上按简单时我想取消选择我所有选定的项目.

这是我取消选择所有项目功能:

private void DeselectAllListViewItems()
{
    MyListView.SelectedItems.Clear();
} 
Run Code Online (Sandbox Code Playgroud)

我尝试使用此函数获取所选索引:

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

但是如果我有几个选定的项目(或一个..),所选的索引永远不会是-1.那么我如何区分我的mouse click空位而不是项目排?

J3s*_*oon 9

下面的代码效果很好.

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

WPF列表框通过单击空白点删除选择