[英]Reset WPF Datagrid scrollbar position
When changing the .DataContext property of a Datagrid (to a new source) the selected item gets cleared, but the scrollbar position is retained. 更改Datagrid的.DataContext属性(到新源)时,将清除所选项目,但保留滚动条位置。 To avoid this I call .ScrollIntoView(.Item(0), after changing the datacontext, to move the scrollbar upwards. But it displays the wrong page for a fraction of a second, and when I scroll to the top before changing the datacontext, i have the same problem. 为了避免这种情况,我调用.ScrollIntoView(.Item(0),在更改datacontext之后,向上移动滚动条。但是它会在几分之一秒内显示错误的页面,当我在更改datacontext之前滚动到顶部时,我也有同样的问题。
So how can I change the .DataContext and resetting the scrollbar position at the same time? 那么如何更改.DataContext并同时重置滚动条位置呢?
EDIT: I should mention that my XAML looks like this: 编辑:我应该提到我的XAML看起来像这样:
<DataGrid VirtualizingStackPanel.IsVirtualizing="True" VirtualizingStackPanel.VirtualizationMode="Recycling">
So maybe the virtualizing is the cause. 也许虚拟化可能是原因。
Have you tried calling ScrollToTop
for the ScrollViewer
in the DataContextChanged event? 您是否尝试在DataContextChanged事件中为ScrollViewer
调用ScrollToTop
?
<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 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.