更改键盘输入的默认行为

Change default behaviour for keyboard input

我想禁用 WPF DataGrid UI 控件的默认行为,即在特定单元格上按下回车按钮时,焦点会自动移动到下一个单元格。它应该只提交编辑的新数据,而不是移动到下一个单元格。

我通过安装 PreviewKeyDown 处理程序并使用两个 MoveFocus 调用找到了解决方法。如果没有该解决方法(仅使用 e.Handled = true 语句),编辑后的数据将无法正确提交(单元格将无限期地处于编辑模式)。

XAML:

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

处理程序:

    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));
        }
    }

有人可以帮我找到更好的解决方案吗?

调用CommitEdit()方法提交数据:

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