更改Datagrid的.DataContext属性(到新源)时,所选项目将被清除,但保留滚动条位置。为了避免这种情况,我调用.ScrollIntoView(.Item(0),在更改datacontext之后,向上移动滚动条。但是它会在几分之一秒内显示错误的页面,当我在更改datacontext之前滚动到顶部时,我有同样的问题。
那么如何更改.DataContext并同时重置滚动条位置呢?
编辑:我应该提一下,我的XAML看起来像这样:
<DataGrid VirtualizingStackPanel.IsVirtualizing="True" VirtualizingStackPanel.VirtualizationMode="Recycling">
所以也许虚拟化是原因。
答案 0 :(得分:10)
您是否尝试在DataContextChanged事件中为ScrollToTop
调用ScrollViewer
?
<DataGrid VirtualizingStackPanel.IsVirtualizing="True"
VirtualizingStackPanel.VirtualizationMode="Recycling"
DataContextChanged="dataGrid_DataContextChanged"
...>
private void dataGrid_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
ScrollViewer scrollViewer = GetVisualChild<ScrollViewer>(dataGrid);
if (scrollViewer != null)
{
scrollViewer.ScrollToTop();
}
}
GetVisualChild
private static T GetVisualChild<T>(DependencyObject parent) where T : Visual
{
T child = default(T);
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++)
{
Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
child = v as T;
if (child == null)
{
child = GetVisualChild<T>(v);
}
if (child != null)
{
break;
}
}
return child;
}