Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to acess DataGridCell on Right click on WPF DataGrid

I have a WPF DataGrid and have a event MouseRightButtonUp for right click on DataGrid. How to access DataGridCell inside the event handler?

private void DataGrid_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
      //access DataGridCell on which mouse is right clicked
      //Want to access cell here
}
like image 687
Kishor Avatar asked Nov 19 '12 07:11

Kishor


1 Answers

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.
}
like image 160
Andy Avatar answered Nov 08 '22 22:11

Andy