【发布时间】:2019-05-31 14:34:02
【问题描述】:
我的要求是滚动 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 次中,焦点有效,但有几次随机无效
【问题讨论】: