Я не уверен, почему ваш обработчик события LoadingRow находится в вашей ViewModel. Если вы используете MVVM, ваши viewModels не должны манипулировать визуальными элементами, такими как DataGrid и DataGridCell, а только базовыми бизнес-данными.
В вашем случае вы можете подписаться на событие LoadingRow, например:
<DataGrid ItemsSource="{Binding BusinessObjectExemples}" LoadingRow="DataGrid_LoadingRow" />
и затем в вашем коде (файл xaml.cs):
private void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
if (sender is DataGrid dataGrid && e.Row is DataGridRow row)
{
//You can now access your dataGrid and the row
row.Tag = row.GetIndex().ToString();
//The grid is still loading row so it is too early to set the current cell.
}
}
Что вы можете сделать, это подписаться на загруженное событие вашей сетки и установить туда selectedCell:
private void Grid_Loaded(object sender, RoutedEventArgs e)
{
//Adapt the logic for the cell you want to select
var dataGridCellInfo = new DataGridCellInfo(this.Grid.Items[11], this.Grid.Columns[1]);
//The grid must be focused in order to be directly editable once a cell is selected
this.Grid.Focus();
//Setting the SelectedCell might be neccessary to show the "Selected" visual
this.Grid.SelectedCells.Clear();
this.Grid.SelectedCells.Add(dataGridCellInfo);
this.Grid.CurrentCell = dataGridCellInfo;
}
Вы также можете выполнить ту же логику c с помощью кнопки.
Xaml:
<DataGrid x:Name="Grid" ItemsSource="{Binding BusinessObjectExemples}"
Loaded="Grid_Loaded" SelectionUnit="Cell" AutoGenerateColumns="False"
LoadingRow="DataGrid_LoadingRow">
А если какая-то часть обработки связана с бизнесом и должна быть в вашей viewModel. Затем вы можете вызвать команду или запустить publi c методы из DataGrid_LoadingRow в вашем коде позади.