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