Datagrid滚动条位置

Datagrid滚动条位置

本文介绍了重置WPF Datagrid滚动条位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

在更改Datagrid的.DataContext属性(到新的源)时,将清除选定的项目,但保留滚动条的位置.为避免这种情况,更改数据上下文后,我调用.ScrollIntoView(.Item(0)来向上移动滚动条.但是它会显示错误的页面一秒钟,并且当我在更改数据上下文之前滚动到顶部时,我有同样的问题.

When changing the .DataContext property of a Datagrid (to a new source) the selected item gets cleared, but the scrollbar position is retained. 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.

那么如何更改.DataContext并同时重置滚动条位置?

So how can I change the .DataContext and resetting the scrollbar position at the same time?

我应该提到我的XAML如下:

I should mention that my XAML looks like this:

<DataGrid VirtualizingStackPanel.IsVirtualizing="True" VirtualizingStackPanel.VirtualizationMode="Recycling">

所以也许是虚拟化的原因.

So maybe the virtualizing is the cause.

推荐答案

您是否尝试过在DataContextChanged事件中为ScrollViewer调用ScrollToTop?

Have you tried calling ScrollToTop for the ScrollViewer in the DataContextChanged event?

<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;
}

这篇关于重置WPF Datagrid滚动条位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 14:25