【问题标题】:WPF DataGrid Scroll To Top after Sort排序后WPF DataGrid滚动到顶部
【发布时间】:2011-11-03 04:21:22
【问题描述】:

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

对于这个应用程序,我需要在任何排序后滚动到网格的顶部。

我尝试过像这样处理排序事件

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

但这似乎在排序发生之前触发并且不执行滚动。

想法?

【问题讨论】:

    标签: .net wpf vb.net wpfdatagrid


    【解决方案1】:

    我不知道VB中的语法,但我认为应该差不多。这是在 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 中显示的项目。

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

    希望这会有所帮助。干杯

    编辑:在发布之前我忘记提及的另一件事...... 您可能需要覆盖 DataGrid 中的 OnSorting 方法。

    因此,在您的 DataGrid 的某些派生类中将实现此新功能,您将拥有此覆盖。

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

    【讨论】:

    • 谢谢@Beljoda。做到了。
    • 为什么您严重依赖线程,您还应该确保在以编程方式滚动后调用myDataGrid.UpdateLayout()
    【解决方案2】:

    这是 VB 语法。

    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
    

    【讨论】:

      猜你喜欢
      • 2017-05-12
      • 1970-01-01
      • 2015-07-09
      • 2017-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-24
      • 2011-10-06
      相关资源
      最近更新 更多