编程语言
首页 > 编程语言> > c# – 如何访问DataGridCell右键单击WPF DataGrid

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.
}

标签:c,wpf,datagrid,wpfdatagrid,right-click
来源: https://codeday.me/bug/20190718/1494338.html