WPF DataGrid lost focus after row delete

感情迁移 提交于 2019-12-23 12:36:52

问题


I am using WPF DataGrid row deletion by keyboard "Delete" key press. However, after the row is deleted, DataGrid lost its focus, and DataGrid.SelectedIndex = -1.

Compared to WinForm datagrid, after a row is deleted, the focus automatically shift to the next focusable row, which is much more reasonable.

By "next focusable", I mean, e.g.:

Row A
Row B
Row C

If we delete Row A, the next focusable will be Row B.
If we delete Row B, the next focusable will be Row C.
If we delete Row C, the next focusable will be Row B (the last row).

How can we achieve the same effect in WPF datagrid?

By the way, the following is an example that focuses on the first row after deletion, which is not ideal, since we wanted it to be the "next focusable row".

    private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (e.RemovedItems.Count > 0)
        {
            DataGrid grid = sender as DataGrid;
            if (grid.SelectedIndex == -1)
            {
                grid.SelectedCells.Clear();
                grid.SelectedIndex = 0;
            }
        }
    }

Any ideas?

Thanks.


回答1:


What are you binding your DataGrid to? Have you tried a CollectionView (MSDN)? That has props like CurrentPosition and the MoveCurrentToNext() method. You could get the current position of the row being deleted and then locate the next one based on the sort order of the CollectionView.

Update: If you're doing MVVM, disable the DataGrid's delete (see this answer) and have your VM remove the item from the collection. You'll know which item is being removed so you should then be able to figure out what the next (or prior) item is. Have your VM expose a SelectedItem property which you'll bind to the DataGrid.SelectedItem. Set the SelectedItem on your VM and the row should be selected in the DataGrid.

It sounds like the WinForms Datagrid handled a lot of this out of the box so you probably feel like you're reinventing the wheel and that this is a lot of work for something that just worked automatically in the "old" UX technology.



来源:https://stackoverflow.com/questions/28963575/wpf-datagrid-lost-focus-after-row-delete

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