c# – 如何访问DataGridCell右键单击WPF DataGrid

我有一个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
}

解决方法:

我从来没有真正喜欢使用可视化树帮助器,但在这种情况下可以使用它.

基本上它的作用是点击测试鼠标下的控件,单击右键并使用可视树辅助类向上导航可视树,直到你击中一个单元格对象.

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.
}
上一篇:列名包含"."的DataTable,如何binding到DataGrid上?


下一篇:c#-在WPF DataGrid单元格编辑期间显示弹出窗口