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

這解決了這個問題。

相關問題