出于某种原因,我从来没有真正喜欢使用可视化树助手,但在这种情况下可以使用它。
基本上它的作用是在单击右键时对鼠标下的控件进行点击测试,并使用可视化树帮助器类向上导航可视化树,直到您点击一个单元格对象。
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.
}