如何在WPF DataGrid上右键单击访问DataGridCell

5

我有一个 WPFDataGrid,并且在右键单击 DataGrid 时会触发 MouseRightButtonUp 事件。如何在事件处理程序中访问 DataGridCell

private void DataGrid_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
      //access DataGridCell on which mouse is right clicked
      //Want to access cell here
}
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.
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接