Search code examples
c#wpfdatagridwpfdatagrid

Change default behaviour for keyboard input


I want to disable the default behavior of the WPF DataGrid UI control, that on pressing the enter button on a specific cell, the focus moves automatically to the next cell. It should just commit the edited new data, but not move to the next cell.

I found a workaround by installing a PreviewKeyDown handler and using two MoveFocus calls. Without that workaround (only with the e.Handled = true statement), the edited data will not committed properly (the cell will stay in the editing mode infinitely).

XAML:

<DataGrid PreviewKeyDown="DataGrid_PreviewKeyDown"... </DataGrid>

Handler:

    private void DataGrid_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        var uiElement = e.OriginalSource as UIElement;
        if (e.Key == Key.Enter && uiElement != null)
        {
            e.Handled = true;
            uiElement.MoveFocus(new TraversalRequest(FocusNavigationDirection.Left));
            uiElement.MoveFocus(new TraversalRequest(FocusNavigationDirection.Right));
        }
    }

Can someone please help me to find a better solution?


Solution

  • Call the CommitEdit() method to commit the data:

    private void DataGrid_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            e.Handled = true;
            ((DataGrid)sender).CommitEdit();
        }
    }