Мое требование - прокрутить сетку данных wpf и перейти к определенной строке и сфокусировать эту строку
Я использую приведенный ниже код для достижения этой цели. Прокрутка к определенной строке работает плавно, но несколько раз фокус не работает
private void FocusNextRow()
{
int index = indexOfRowsToHighlight[indexOfRowToFocus];
MessagesDataGrid.SelectedItem = MessagesDataGrid.Items[index];
MessagesDataGrid.ScrollIntoView(MessagesDataGrid.SelectedItem);
Thread.Sleep(200);
MessagesDataGrid.SelectionUnit = DataGridSelectionUnit.FullRow;
DataGridRow row = MessagesDataGrid.ItemContainerGenerator.ContainerFromIndex(index) as DataGridRow;
DataGridCell cell = GetCell(MessagesDataGrid, row, 0);
cell.Focus();
}
private static DataGridCell GetCell(DataGrid dataGrid, DataGridRow rowContainer, int column)
{
if (rowContainer != null)
{
DataGridCellsPresenter presenter = FindVisualChild<DataGridCellsPresenter>(rowContainer);
// try to get the cell but it may possibly be virtualized
DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
if (cell == null)
{
cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
}
return cell;
}
return null;
}
private static T FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
{
for(int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if (child != null && child is T)
return (T)child;
else
{
T childOfChild = FindVisualChild<T>(child);
if (childOfChild != null)
return childOfChild;
}
}
return null;
}
Из 100 раз фокусировка работает в 90 раз, но случайным образом не работает