WPF DataGrid - get row number which mouse cursor is on

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

    I need the DataGridRow below the mouse, in one of my applications, to highlight it. Each Cell has a DataTemplate

    
            
                
                
                
            
        
    

    To get the coordinates of a DataGridCell, I'm looking for an image of the DataTemplate while moving the mouse. If an Image has been found, I'm able to move up the VisualTree to find my cell and it's coordinates (row, column) when I got an Image. It's not a very generic code - just good for my use.

    private void DragDrop_PreviewDragOver(object sender, DragEventArgs e)
        {
            if (e.OriginalSource.GetType() != typeof(Image))
            {
                return;
            }
    
            Point destination = GetCellLocation((DataGrid)sender, (StackPanel)((Image)e.OriginalSource).Parent);
        }
    

    and this

    private Point GetCellLocation(DataGrid datagrid, StackPanel stackpanel)
        {
            DataGridCell cell = (DataGridCell)((ContentPresenter)stackpanel.TemplatedParent).Parent;
            int column = cell.Column.DisplayIndex;
            int row = ((DataGrid)datagrid).Items.IndexOf(stackpanel.DataContext);
    
            return new Point(column, row);
        }
    

    Hope it helps

提交回复
热议问题