Search code examples
c#wpfdatagridfocusuielement

Interpret Enter as Tab with selection


I use this code on Enter keypress to move focus to next like the Tab does in a datagrid.

uiElement.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));

At the end of any row while hitting enter moves the focus to the next line but the selection stays where it was. On the other hand using Tab brings the selection with the focus.

Is there a way to move the selection aswell with some adjustments?

Matt Hamilton's answer is great but not doing the selection.


Solution

  • What you could do, instead of trying to programmatically switch focus, is simulating a tab key press each time the enter key is pressed inside the DataGrid. It would then look something like this:

    private void DataGrid_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            var dataGrid = (DataGrid)sender;
            var keyEventArgs = new KeyEventArgs(Keyboard.PrimaryDevice, PresentationSource.FromVisual(dataGrid), 0, Key.Tab)
            {
                RoutedEvent = Keyboard.KeyDownEvent,
            };
    
            dataGrid.RaiseEvent(keyEventArgs);
            e.Handled = true;
        }
    }