WPF DataGrid 排序后滚动到顶部 [英] WPF DataGrid Scroll To Top after Sort

查看:42
本文介绍了WPF DataGrid 排序后滚动到顶部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用数据网格的 .Net 4.0 WPF 应用程序.当前按列排序后,网格的滚动位置保持在排序前的位置.

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.

想法?

推荐答案

我不知道 VB 中的语法,但我认为应该差不多.这是在 C# 中:

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

通常,DataGrid 的第一个 Visual 子代是它的装饰器,而装饰器的子代是 ScrollViewer.从 ScrollViewer,您可以操作 dataGrid 中显示的项目.

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.

哦... VisualTreeHelper 可帮助您从一个视觉元素导航到您所在的当前元素的内部或外部.我认为它在 System.Windows.Media 中.

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.

希望这有帮助.干杯

在我发布这篇文章之前我忘记提及的另一件事......您可能需要覆盖 DataGrid 中的 OnSorting 方法.

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

因此,在您将实现此新功能的 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();
    }
}

这篇关于WPF DataGrid 排序后滚动到顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆