【问题标题】:Change default behaviour for keyboard input更改键盘输入的默认行为
【发布时间】:2018-08-27 13:54:55
【问题描述】:

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

我通过安装 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));
        }
    }

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

【问题讨论】:

    标签: c# wpf datagrid wpfdatagrid


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2011-09-16
      • 1970-01-01
      • 2012-03-07
      • 2012-05-26
      • 2017-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-30
      相关资源
      最近更新 更多