如何访问DataGrid单元格右键单击WPF DataGrid

时间:2012-11-19 07:33:25

标签: c# wpf datagrid wpfdatagrid right-click

我有一个WPF DataGrid并且有一个事件MouseRightButtonUp可以右键点击DataGrid。如何在事件处理程序中访问DataGridCell

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

1 个答案:

答案 0 :(得分: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.
}