Unselect GridView.Item on click if already selecte

2019-05-19 03:00发布

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?

3条回答
Explosion°爆炸
2楼-- · 2019-05-19 03:33

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.

查看更多
爷的心禁止访问
3楼-- · 2019-05-19 03:53

I think instead of Delay its better to use this:

Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => gridView.SelectedItem = null);
查看更多
来,给爷笑一个
4楼-- · 2019-05-19 03:55

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.

查看更多
登录 后发表回答