I am looking to get the row number of which the mouse cursor is on in a DataGrid (So basically on a MouseEnter event) so I can get the DataGridRow item of which the ItemSour
If you access the DataGridRow
object that your mouse is over, then you can find its row index using the DataGridRow.GetIndex method:
private void Event(object sender, MouseEventArgs e)
{
HitTestResult hitTestResult =
VisualTreeHelper.HitTest(m_DataGrid, e.GetPosition(m_DataGrid));
DataGridRow dataGridRow = hitTestResult.VisualHit.GetParentOfType();
int index = dataGridRow.GetIndex();
}
The GetParentOfType
method is actually an extension method that I use:
public static T GetParentOfType(this DependencyObject element) where T : DependencyObject
{
Type type = typeof(T);
if (element == null) return null;
DependencyObject parent = VisualTreeHelper.GetParent(element);
if (parent == null && ((FrameworkElement)element).Parent is DependencyObject) parent = ((FrameworkElement)element).Parent;
if (parent == null) return null;
else if (parent.GetType() == type || parent.GetType().IsSubclassOf(type)) return parent as T;
return GetParentOfType(parent);
}