5

我有一个右键单击WPF DataGrid的事件。如何访问事件处理程序内部?MouseRightButtonUpDataGridDataGridCell

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

1 回答 1

12

出于某种原因,我从来没有真正喜欢使用可视化树助手,但在这种情况下可以使用它。

基本上它的作用是在单击右键时对鼠标下的控件进行点击测试,并使用可视化树帮助器类向上导航可视化树,直到您点击一个单元格对象。

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.
}
于 2012-11-19T16:49:34.543 回答