开发者

Reset WPF Datagrid scrollbar position

开发者 https://www.devze.com 2023-02-14 06:00 出处:网络
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 cha

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.

So how can I change the .Dat开发者_JS百科aContext and resetting the scrollbar position at the same time?

EDIT: I should mention that my XAML looks like this:

<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?

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

精彩评论

暂无评论...
验证码 换一张
取 消