How can I unselect item in ListView?

自作多情 提交于 2019-12-04 03:01:35

问题


I have a ListView with a couple of items in it. When the ListView looses focus, the last selected ListViewItem is still "selected" with a gray background.
I would like to achieve that on ListView.FocusLost, the selection is gone and therefore the ListView.SelectedIndexChanged event will occur.
Any ideas?

I am using .NET CF 3.5.


回答1:


Suppose you are accessing the ListView from a parent form/control.

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.




回答2:


myListView.SelectedItems.Clear();



回答3:


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.

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;
}



回答4:


this is easier.

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



回答5:


Another effective way to approach this would be:

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



回答6:


If you are using EditItemTemplate, rather than ItemTemplate, you may have been trying to figure out why ListView1.SelectedIndex = -1; hasn't been working. It's because you need to use ListView1.EditIndex = -1;




回答7:


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):

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

Regards




回答8:


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


来源:https://stackoverflow.com/questions/7089235/how-can-i-unselect-item-in-listview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!