WPF DataGrid - get row number which mouse cursor is on

前端 未结 4 1932
情歌与酒
情歌与酒 2021-01-18 23:24

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

4条回答
  •  孤街浪徒
    2021-01-18 23:48

    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);
    }
    

提交回复
热议问题