Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF DataGrid Scroll To Top after Sort

I have a .Net 4.0 WPF application using a data grid. Currently after sorting by a column, the scroll position of the grid stays where it was before the sort.

For this application, I need to scroll to the top of the grid after any sort.

I've tried handling the sorting event like this

    Private Sub myDataGrid_Sorting(sender As Object, e As System.Windows.Controls.DataGridSortingEventArgs) Handles myDataGrid.Sorting
            myDataGrid.ScrollIntoView(myDataGrid.Items(0))
    End Sub

But this appears to fire before the sorting takes place and doesn't perform the scroll.

Thoughts?

like image 995
bkstill Avatar asked Aug 24 '11 21:08

bkstill


1 Answers

I don't know the syntax in VB, but I think it should be about the same. Here it is in C#:

var border = VisualTreeHelper.GetChild(myDataGrid, 0) as Decorator;
if (border != null)
{
    var scrollViewer = border.Child as ScrollViewer;
    scrollViewer.ScrollToTop();
}

Usually, the first Visual child of a DataGrid is its decorator, and the child of the decorator is the ScrollViewer. From the ScrollViewer, you can manipulate what items are shown in the dataGrid.

Oh... And the VisualTreeHelper help you navigate from one visual element to the next inside or outside the current one you're in. It's in System.Windows.Media I think.

Hope this helped. Cheers

Edit: One other thing I forgot to mention before I posted this... You might need to override the OnSorting method in the DataGrid.

So in some derived class from DataGrid of yours that will be implementing this new functionality, you'd have this override.

protected override void OnSorting(DataGridSortingEventArgs eventArgs)
{
    base.OnSorting(eventArgs);

    var border = VisualTreeHelper.GetChild(myDataGrid, 0) as Decorator;
    if (border != null)
    {
        var scrollViewer = border.Child as ScrollViewer;
        scrollViewer.ScrollToTop();
    }
}
like image 113
Beljoda Avatar answered Nov 11 '22 16:11

Beljoda