我的要求是在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;
}
在90倍于100倍的对焦中,有效果,但有几次随机性则无效
答案 0 :(得分:0)
可能正在虚拟化! 调用FocusNextRow函数时,请检查ItemContainerGenerator的状态
MessagesDataGrid.ItemContainerGenerator.ContainerFromIndex(index) as DataGridRow;
答案 1 :(得分:0)
我为此问题找到了两种解决方案 1.禁用数据网格的行虚拟化属性。但是它会严重影响性能。 2.检查FindVisualChild()是否能够找到行容器,如果找不到,则在该情况下调用rowcontainer.ApplyTemplate()方法,此方法ApplyTemplate()确保在可视树中创建行。更有效的方式