简体   繁体   English

如何取消选择 ListView 中的项目?

[英]How can I unselect item in ListView?

I have a ListView with a couple of items in it.我有一个 ListView,里面有几个项目。 When the ListView looses focus, the last selected ListViewItem is still "selected" with a gray background.当 ListView 失去焦点时,最后选择的 ListViewItem 仍处于“选中”状态,背景为灰色。
I would like to achieve that on ListView.FocusLost, the selection is gone and therefore the ListView.SelectedIndexChanged event will occur.我想在 ListView.FocusLost 上实现这一点,选择消失了,因此会发生 ListView.SelectedIndexChanged 事件。
Any ideas?有任何想法吗?

I am using .NET CF 3.5.我正在使用 .NET CF 3.5。

Suppose you are accessing the ListView from a parent form/control.假设您正在从父窗体/控件访问 ListView。

You can add this piece of code in the form's/control's constructor/load event:您可以在表单/控件的构造函数/加载事件中添加这段代码:

this.myListView.LostFocus += (s, e) => this.myListView.SelectedIndices.Clear();

Ok, so in your case, you would replace that delegate with:好的,所以在您的情况下,您可以将该委托替换为:

if (this.myListView.SelectedIndices.Count > 0)
    for (int i = 0; i < this.myListView.SelectedIndices.Count; i++)
    {
        this.myListView.Items[this.myListView.SelectedIndices[i]].Selected = false;
    }

You can give the code a nicer form, btw.顺便说一句,您可以为代码提供更好的形式。

myListView.SelectedItems.Clear();

I know this is late but in case someone else needed the solution I would like to add to the solution.我知道这已经晚了,但如果其他人需要我想添加到解决方案中的解决方案。

You need to set the Focused property to false to avoid deselected items having focus.您需要将 Focused 属性设置为 false 以避免取消选中的项目具有焦点。

for (int i = 0; i < this.myListView.SelectedIndices.Count; i++)
{
    this.myListView.Items[this.myListView.SelectedIndices[i]].Selected = false;
    this.myListView.Items[this.myListView.SelectedIndices[i]].Focused = false;
}

Another effective way to approach this would be:解决此问题的另一种有效方法是:

foreach (ListViewItem i in myListView.SelectedItems)
{
    i.Selected = false;
}

this is easier.这更容易。

this.myListView.SelectedIndex = -1;
this.myListView.Update();

If you are using EditItemTemplate, rather than ItemTemplate, you may have been trying to figure out why ListView1.SelectedIndex = -1;如果您使用的是 EditItemTemplate,而不是 ItemTemplate,您可能一直在试图弄清楚为什么 ListView1.SelectedIndex = -1; hasn't been working.一直没有工作。 It's because you need to use ListView1.EditIndex = -1;这是因为您需要使用 ListView1.EditIndex = -1;

You can try it:你可以试试:

MyList.ItemSelected += (sender, e) => {
    ((ListView)sender).SelectedItem = null;
};

or if you have the OnSelection created in your View code behind(xaml.cs):或者如果您在后面的视图代码中创建了 OnSelection (xaml.cs):

 private void OnSelection(object sender, SelectedItemChangedEventArgs e)
        {
           ((ListView)sender).SelectedItem = null;
        }

Regards问候

if (listView1.SelectedItems.Count > 0)
    for (int i = 0; i < listView1.SelectedItems.Count; i++)
    {
        listView1.SelectedItems[i].Selected = false;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM