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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30737097/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 13:11:41  来源:igfitidea点击:

WPF; How Deselect all my selected items when click on empty space in my ListView

wpflistview

提问by Verint Verint

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

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

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 clickis on empty space and not on item row ?

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

回答by J3soon

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

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