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 so开发者_C百科rt.
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?
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();
}
}
Here's the VB Syntax.
Private Sub myDataGrid_Sorting(sender As Object, e As System.Windows.Controls.DataGridSortingEventArgs) Handles myDataGrid.Sorting
Dim border As Decorator = VisualTreeHelper.GetChild(myDataGrid, 0)
If border IsNot Nothing Then
Dim scrollViewer As ScrollViewer = border.Child
scrollViewer.ScrollToTop()
End If
End Sub
精彩评论