简体   繁体   中英

ListView select and deselect on click (no Ctrl + click needed)

Normal ListView in UWP (with SelectionMode="Single") selects item when you click it and deselects item when you Ctrl + click it.

I want to change the deselect functionality so that you do not need to press Ctrl to deselect item. Just click selected item again to remove selection.

It seems that when setting SelectionMode="Multiple", clicking item again deselects it like I wanted but I do not want to get multiple items selected.

UPDATE

This is how im doing right now. So I'm listening SelectionChanged event, and when event is fired, im getting the selected item from ListView selectedItem property.

<ListView ItemsSource="{x:Bind ViewModel.Cars}" SelectedItem="{Binding SelectedCar, Mode=TwoWay}" SelectionMode="Single">
    <interactivity:Interaction.Behaviors>
        <core:EventTriggerBehavior EventName="SelectionChanged">
            <core:InvokeCommandAction Command="{Binding CarSelectedCommand}" />
        </core:EventTriggerBehavior>
    </interactivity:Interaction.Behaviors>
    <ListView.ItemTemplate>
        <DataTemplate x:DataType="model:ICar">
            <StackPanel>
                <TextBlock Text="{x:Bind Name}"/>
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

Enable IsItemClickEnabled in the Listview. When it is fired check whether the item clicked is already selected and deselect it. I have tested it and the click event occurs before the selection so you should be fine.

Set multiple SelectionMode and hide selection checkboxes

<ListView SelectionMode="Multiple" IsMultiSelectCheckBoxEnabled="False" SelectionChanged="_listView_SelectionChanged" >

This event will be raised twice for every selection

Item prevSelection = null;
    private void _listView_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        Item selected = null;
        foreach (var item in e.AddedItems)
        {
            selected = item as Item;
        }
        if (selected != null && selected != prevSelection)
        {
            prevSelection = selected;
            _listView.DeselectRange(new ItemIndexRange(0, (uint)_collection.Count));
            _listView.SelectedItem = selected; //will rise event again
            selected = prevSelection = null;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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