Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF DataGrid lost focus after row delete

Tags:

c#

wpf

datagrid

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.

like image 863
RainCast Avatar asked Nov 09 '22 17:11

RainCast


1 Answers

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.

like image 124
KornMuffin Avatar answered Nov 15 '22 12:11

KornMuffin