Unselect GridView.Item on click if already selected

主宰稳场 提交于 2019-12-07 12:04:57

问题


I know this seems rather simple, and that's what I thought too, but it actually isn't. I have a GridView, with SelectionMode="Single", and I want to simply unselect a selected item by clicking on it. Problem is, SelectionChanged doesn't fire when you select an item that is already selected. I've tried having an int equal to the GridView's SelectedIndex on each SelectionChanged, and then check on Grid_Tapped to see if PreviousSelectedIndex == CurrentlySelectedIndex, but the SelectionChanged event fires nanoseconds before the Grid_Tapped, so it doesn't work. Any ideas?


回答1:


Yes it is a bit weird default behavior, you can do the following trick to solve that (there are many ways)

1.- the XAML

<GridView IsItemClickEnabled="True" ItemClick="IconGridView_ItemClick" SelectionMode="Single">

2.- The event code:

 private async void IconGridView_ItemClick(object sender, ItemClickEventArgs e)
    {
        var gridView = sender as GridView;
        if (e.ClickedItem == gridView.SelectedItem)
        {
            await Task.Delay(100);
            gridView.SelectedItem = null;
        }
    }

If you do not wait a bit, the internals events keep the selected item, with that way it is solved and the SelectedItem is Deselected.




回答2:


I think instead of Delay its better to use this:

Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => gridView.SelectedItem = null);



回答3:


Use the CellClick event.

In example, private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e), e.RowIndex holds the index of the cell that was clicked. All you have to do is check if this index is equal to SelectedIndex.



来源:https://stackoverflow.com/questions/34458244/unselect-gridview-item-on-click-if-already-selected

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