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
}
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.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With