Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deselect ListViewItem programmatically?

I'm stumped with this little problem for a while. The ListView under W10 has some strange behavior I cannot understand. Consider a simple list:

<ListView Name="myList" ItemClick="myList_ItemClick" SelectionChanged="myList_SelectionChanged" IsItemClickEnabled="True">
    <ListView.Items>
        <TextBlock Text="First item"/>
        <TextBlock Text="Second item"/>
        <TextBlock Text="Third item"/>
        <TextBlock Text="Fifth item"/>
    </ListView.Items>
</ListView>

and the code behind:

private void myList_ItemClick(object sender, ItemClickEventArgs e)
{
    Debug.WriteLine("Clicked item");
    ListView list = sender as ListView;
    ListViewItem listItem = list.ContainerFromItem(e.ClickedItem) as ListViewItem;
    listItem.IsSelected = !listItem.IsSelected;
}

private void myList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    Debug.WriteLine($"Selection changed -> added = {e.AddedItems.Count}, removed = {e.RemovedItems.Count}, currently selected = {myList.SelectedItems.Count}");
}

The code above runs very well on W8.1, but on W10 I encounter a problem. Selecting a first item works ok, changing it also, but I cannot deselect an item - listview seems (from debug output) to deselect item and then select it again right away - you can see SelectionChanged event fired twice. Here is sample debug output:

Debug Output

Does somebody know what is going on? How to deselect the item in this case?

like image 281
Romasz Avatar asked Mar 14 '23 09:03

Romasz


1 Answers

I'm assuming that there's a different order of events going on in UWP. Something like this:

Item not selected -> ItemClick event handler -> Item is selected -> SelectionChanged event -> Some other event -> No more SelectionChanged events as that item is already selected.

Item is selected -> ItemClick event handler -> Item is not selected -> SelectionChanged event -> Some other event -> SelectionChanged event fires again as the item is no longer selected.

Here's a bit of a dirty trick to make it work:

private void myList_ItemClick(object sender, ItemClickEventArgs e)
{
    Debug.WriteLine("Clicked item");
    ListView list = sender as ListView;
    ListViewItem listItem = list.ContainerFromItem(e.ClickedItem) as ListViewItem;

    if (listItem.IsSelected)
    {
        listItem.IsSelected = false;
        list.SelectionMode = ListViewSelectionMode.None;
    }
    else
    {
        list.SelectionMode = ListViewSelectionMode.Single;
        listItem.IsSelected = true;
    }
}

EDIT: The behavior for multiple selection already works as expected: the item is deselected on second click. No workarounds needed!

like image 161
Igor Ralic Avatar answered Mar 27 '23 22:03

Igor Ralic