Listview ItemSelectionChanged fires twice?

一曲冷凌霜 提交于 2020-01-28 05:47:24

问题


I have a Winforms App in C# with a ListView control. This ListView shows a list of TO-DO items and I am using the 'ItemSelectionChanged' event to handle updates.

The problem is that the 'ItemSelectionChanged' event fires twice each time I try to make an update.

The ItemSelectionChanged event refreshs the form to represent the updates (ie remove item from list).

Is there a way to disable the event from firing after the refresh?

UPDATE1:

private void listView1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
    {   
        if (e.IsSelected)
        {                
            listView1.Items[e.ItemIndex].Remove();

            listView1.SelectedIndices.Clear();
            listView1.Focus();

            listView1.Update();
        }
        else
        {

        }

    }

回答1:


Yes, it will fire twice. Once because the previously selected item became unselected, again for the newly selected item. You just have to make sure you see the selection event:

    private void listView1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e) {
        if (e.IsSelected) {
            // Update form
            //...
        }
    }



回答2:


Yes just remove the EventHandler at the start of the refresh and add it again after it has finished refreshing

i.e

// Remove handler
listView1.ItemSelectionChanged -= new ListViewItemSelectionChangedEventHandler(listView1_ItemSelectionChanged);

// Do refresh

// Add again
listView1.ItemSelectionChanged += new ListViewItemSelectionChangedEventHandler(listView1_ItemSelectionChanged);



回答3:


I think you need manually unselect the item in the end of your handler.

listView1.SelectedItem = null;




回答4:


Try this:

private void ItemSelect()
{

        if(SelectedItem!=null)
            App.Current.MainPage.Navigation.PushAsync(new Pages.TLAccByCurrency(), true);
        _selectedItem = null;
}


来源:https://stackoverflow.com/questions/3229498/listview-itemselectionchanged-fires-twice

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