In an event handler for a Command for a DataGrid, I get DataGridCell in ExecutedRoutedEventArgs. However, I couldn't figure out how to get its associated DataGrid and DataGridRow. Your help is much appreciated.
You probably want to set some sort of RelativeSource
binding that can get you the "parent grid/row" via a {RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}
, but your question got me thinking...
You could:
Use Reflection:
var gridCell = ....;
var parentRow = gridCell
.GetType()
.GetProperty("RowOwner",
BindingFlags.NonPublic | BindingFlags.Instance)
.GetValue(null) as DataGridRow;
Use the VisualTreeHelper
:
var gridCell = ...;
var parent = VisualTreeHelper.GetParent(gridCell);
while(parent != null && parent.GetType() != typeof(DataGridRow))
{
parent = VisualTreeHelper.GetParent(parent);
}