Search code examples
c#.netwpfdatagridwpfdatagrid

WPF DataGrid make new row TabStop


I have a DataGrid with CanUserAddRows="True". My table has multiple columns; the user can edit the cells and jump to the next one by pressing Tab. When you are at the last column, Tab will take you to the next row.

However, if you are editing a New Row, when you Tab at the last column, the focus will jump to the next control in the windows BEFORE the new row is created.

What I need to happen is the focus to jump to the new created row in the DataGrid. I honestly have no idea where to begin attacking this problem.

EDIT: I should clarify that the first column of the new row is the one that should get the focus (Imagine someone filling the grid just with the keyboard, using tab).


Solution

  • You could handle the PreviewKeyDown event for the DataGrid to intercept the TAB keypress and programmatically press the ENTER key:

    <DataGrid x:Name="dg" ... PreviewKeyDown="dg_PreviewKeyDown" />
    

    private void dg_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Tab)
        {
            e.Handled = true;
    
            var key = Key.Enter;
            var target = Keyboard.FocusedElement;
            var routedEvent = Keyboard.KeyDownEvent;
    
            dg.RaiseEvent(new KeyEventArgs(Keyboard.PrimaryDevice, PresentationSource.FromVisual(dg), 0, key)
            {
                RoutedEvent = routedEvent
            });
        }
    }