我正面临着与问题ScrollIntoView for WPF DataGrid (MVVM)类似的问题。与链接的问题相同,只要SelectedItem
发生更改,我都将使DataGrid滚动到所选内容,此外,我还要在此处移动焦点。
answer提供了一种使用阴影SelectedItem
附加属性使SelectingItem
保持可见的解决方案:
// 'SelectingItem' attached property changed callback
static void OnSelectingItemChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var grid = sender as DataGrid;
if (grid == null || grid.SelectedItem == null) return;
grid.Dispatcher.InvokeAsync(() =>
{
grid.UpdateLayout();
grid.ScrollIntoView(grid.SelectedItem, null);
FocusSelectedRow(grid); // to be implemented
});
}
如何也可以集中显示新选择的行/列? cell.Focus()
列的调用DataGridTemplateColumn
的strightforward解决方案失败:
static void FocusSelectedRow(DataGrid dg)
{
if (dg.ItemContainerGenerator.ContainerFromItem(dg.SelectedItem) is DataGridRow row)
{
row.ApplyTemplate();
var presenter = row.GetVisualChild<DataGridCellsPresenter>();
if (presenter.ItemContainerGenerator.ContainerFromIndex(column?.DisplayIndex ?? 0) is DataGridCell cell)
{
cell.Focus(); // does not work properly for DataGridTemplateColumns!
}
}
}
使用上述解决方案时,该单元格仅针对非DataTemplate
列正确地聚焦,从而使GUI交互混乱。对于DataTemplate
列,它会创建反馈循环-单击此类列中的单元格时,它也会更改SelectedItem
。依次触发回调,cell.Focus()
吞下原始事件,使所有输入元素(例如Button
)都无法交互(直到单击 second 为止)。我该如何解决选择焦点问题?