WPF DataGrid - get row number which mouse cursor is on

前端 未结 4 1974
情歌与酒
情歌与酒 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:53

    OK, I found the answer to be here...

    http://www.scottlogic.com/blog/2008/12/02/wpf-datagrid-detecting-clicked-cell-and-row.html

    Don't be confused by the article title..

    For my solution I basically used

    private void MouseOverEvent(object sender, MouseEventArgs e)
    {
            DependencyObject dep = (DependencyObject)e.OriginalSource;
    
             // iteratively traverse the visual tree
             while ((dep != null) &&
                     !(dep is DataGridCell) &&
                     !(dep is DataGridColumnHeader))
             {
                dep = VisualTreeHelper.GetParent(dep);
             }
    
             if (dep == null)
                return;
    
             if (dep is DataGridColumnHeader)
             {
                DataGridColumnHeader columnHeader = dep as DataGridColumnHeader;
                // do something
             }
    
             if (dep is DataGridCell)
             {
                DataGridCell cell = dep as DataGridCell;
    
                // navigate further up the tree
                while ((dep != null) && !(dep is DataGridRow))
                {
                   dep = VisualTreeHelper.GetParent(dep);
                }
    
                DataGridRow row = dep as DataGridRow;
    
               //!!!!!!!!!!!!!* (Look below) !!!!!!!!!!!!!!!!!
    
             }
    
      • Now you can obtain your own object by using row.Item, and bingo, its on the correct row index

    So all about using the mouse original source and going up he VisualTree until you get to the right element.

提交回复
热议问题