2012-11-19 97 views
3

我有一個WPFDataGrid並有一個事件MouseRightButtonUp右鍵點擊DataGrid。如何在事件處理程序中訪問DataGridCell如何訪問DataGridCell上點擊WPF DataGrid

private void DataGrid_MouseRightButtonUp(object sender, MouseButtonEventArgs e) 
{ 
     //access DataGridCell on which mouse is right clicked 
     //Want to access cell here 
} 

回答

10

我從來不喜歡使用視覺樹幫手出於某種原因,但在這種情況下可以使用它。

基本上它所做的就是點擊鼠標右鍵來測試控件,並使用可視樹幫助程序類向上瀏覽可視樹,直到點擊一個單元格對象。

private void DataGrid_MouseRightButtonUp_1(object sender, System.Windows.Input.MouseButtonEventArgs e) 
{ 
    var hit = VisualTreeHelper.HitTest((Visual)sender, e.GetPosition((IInputElement)sender)); 
    DependencyObject cell = VisualTreeHelper.GetParent(hit.VisualHit); 
    while (cell != null && !(cell is System.Windows.Controls.DataGridCell)) cell = VisualTreeHelper.GetParent(cell); 
    System.Windows.Controls.DataGridCell targetCell = cell as System.Windows.Controls.DataGridCell; 

    // At this point targetCell should be the cell that was clicked or null if something went wrong. 
} 
+0

非常感謝好友! – Kishor