Maestro
Maestro

Reputation: 9508

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. 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 .DataContext 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.

Upvotes: 3

Views: 8908

Answers (1)

Fredrik Hedblad
Fredrik Hedblad

Reputation: 84657

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

Upvotes: 15

Related Questions