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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13449413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 06:16:31  来源:igfitidea点击:

How to acess DataGridCell on Right click on WPF DataGrid

c#wpfdatagridwpfdatagridright-click

提问by Kishor

I have a WPFDataGridand have a event MouseRightButtonUpfor right click on DataGrid. How to access DataGridCellinside the event handler?

我有一个WPFDataGrid并且有一个MouseRightButtonUp右键单击的事件DataGrid。如何访问DataGridCell事件处理程序内部?

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

回答by Andy

I never really like using the visual tree helper for some reason but in cases like this it can be used.

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

Basically what it does is hit test the control under the mouse as the right button is clicked and use the visual tree helper class to navigate up the visual tree until you hit a cell object.

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

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