2012-05-14 23 views
2

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

那么我该如何解决这个问题?右键单击时是否可以强制丢失焦点?或者我可以使用DataGrid上的某些特殊属性?我发现这个:WPF DataGrid CellEditEnding - DataSet Not Updating Till Row Lost Focus它使每个单元的DataGrid承诺,而不是每行的基础,但它不能解决我的问题,因为用户仍然可以失去一些数据(虽然只有一个单元格而不是一整排))

+1

确保[Keyboard.ClearFocus](http://msdn.microsoft.com/en-us/library/system.windows.input.keyboard.clearfocus.aspx)或将该窗口聚焦在[PreviewMouseDown](http:///msdn.microsoft.com/en-us/library/system.windows.uielement.previewmousedown.aspx)的帮助? – LPL

回答

2

我使用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(); 
     } 

这解决了这个问题。