WPF DataGrid: How to Determine the Current Row Index?

Try this (assuming the name of your grid is "my_dataGrid"):

var currentRowIndex = my_dataGrid.Items.IndexOf(my_dataGrid.CurrentItem);

Normally, you'd be able to use my_dataGrid.SelectedIndex, but it seems that with the CurrentCellChanged event, the value of SelectedIndex always displays the previously selected index. This particular event seems to fire before the value of SelectedIndex actually changes.


The accepted solution will work until you have no reference-duplicates in the ItemsSource, otherwise you will get index of the object's first occurrence.

The solution from BRAHIM Kamel will work until you have a selection, otherwise(if you click twice and deselect a cell/row) you will not have a SelectedIndex.

With YourDataGrid.ItemContainerGenerator.ContainerFromItem( _dataItemFromCurentCell ) as DataGridRow you will get by duplicates always the last occurrence of data item.

I would handle DataGrid.PreviewMouseLeftButtonDown event and search in handler the visual tree up to a DatagridRow, which has DatagridRow.GetIndex() method. So you will get always the right row index.

<DataGrid ... PreviewMouseLeftButtonDown="Previe_Mouse_LBtnDown" >
    ...
</DataGrid>

private void Previe_Mouse_LBtnDown(object sender, MouseButtonEventArgs e)
{
    DataGridRow dgr = null;
    var visParent = VisualTreeHelper.GetParent(e.OriginalSource as FrameworkElement);
    while (dgr == null && visParent != null)
    {
        dgr = visParent as DataGridRow;
        visParent = VisualTreeHelper.GetParent(visParent);
    }
    if (dgr == null) { return; }

    var rowIdx=dgr.GetIndex();
}