获取包含光标的WPF Datagrid行的行索引

获取包含光标的WPF Datagrid行的行索引,wpf,datagrid,Wpf,Datagrid,如何获取WPF中具有键盘或鼠标焦点的DataGrid行的行索引。我不想要DataGrid.SelectedIndex或DataGrid.SelectedItem,因为当单元格处于编辑模式时,它只返回-1 提前谢谢 您可以使用此帮助器方法获取行索引: public static class DataGridHelper { static public int GetRowIndex(DataGrid dataGrid, DataGridCellInfo dataGridCellInfo)

如何获取WPF中具有键盘或鼠标焦点的
DataGrid
行的行索引。我不想要
DataGrid.SelectedIndex
DataGrid.SelectedItem
,因为当单元格处于编辑模式时,它只返回-1


提前谢谢

您可以使用此帮助器方法获取行索引:

public static class DataGridHelper
{
    static public int GetRowIndex(DataGrid dataGrid, DataGridCellInfo dataGridCellInfo)
    {
        DataGridRow dgrow = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromItem(dataGridCellInfo.Item);
        if (dgrow != null)
            return dgrow.GetIndex();

        return -1;
    }
}
在适当的事件中这样使用它:

int rowIndex = DataGridHelper.GetRowIndex(yourDataGrid, yourDataGrid.SelectedCells[0]);

非常感谢你,艾瑞克!!我很快就会试试的。