【问题标题】:in WPF DataGrid how to force lost focus (and thereby commit) of a datagrid row when rightclicking outside it在 WPF DataGrid 中,如何在数据网格行外部右键单击时强制失去焦点(并因此提交)
【发布时间】:2012-05-22 00:55:12
【问题描述】:

我有一个带有可编辑单元格的 DataGrid。当行失去焦点时,属性更改事件会触发,我通过将更改提交到实体对象并最终提交到数据库来处理它。 用户可以在数据网格外部右击并从上下文菜单中选择。一些上下文菜单项依赖于数据网格中的数据(准确地说,它们依赖于提交的数据)。 但是,问题在于 DataGrid 外部的右键单击不会从 DataGrid 中移除焦点。这意味着不会提交对当前行的更改。这意味着用户会感到惊讶,因为菜单项命令处理的数据与屏幕上显示的数据不同。 我意识到这就是 DataGrid 的工作方式。但是,我也意识到用户永远无法理解这一点。

那么我该如何解决呢?右键单击时可以强制失去焦点吗?或者我可以使用 DataGrid 上的一些特殊属性吗?

(我发现了这个:WPF DataGrid CellEditEnding - DataSet Not Updating Till Row Lost Focus 这使得 DataGrid 以每个单元格而不是每行为基础提交,但它并没有解决我的问题,因为用户仍然可能丢失一些数据(尽管只有一个单元格而不是整行))

【问题讨论】:

标签: wpf wpfdatagrid


【解决方案1】:

我使用了 LPL 的建议,并创建了一个事件处理程序:

 private void ViewUserControl_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {            
            // The purpose of this is to make sure that before the context menu on the outer datagrid is run, the row in the inner datagrid is committed (otherwise we might create orders with different quantities than what the user sees on the screen)
            Keyboard.ClearFocus();
        }

这解决了问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-05
    • 2019-07-23
    • 2013-04-03
    相关资源
    最近更新 更多