【发布时间】:2017-05-12 19:36:44
【问题描述】:
我有一个包含许多项目的 DataGrid,我需要以编程方式滚动到 SelectedItem。我在 StackOverflow 和 Google 上搜索过,似乎解决方法是 ScrollIntoView,如下:
grid.ScrollIntoView(grid.SelectedItem)
向上或向下滚动 DataGrid 直到选中的项目成为焦点。但是,根据相对于所选项目的当前滚动位置,所选项目可能最终成为 DataGrid 的 ScrollViewer 中的最后一个可见项目。我希望所选项目将成为 ScrollViewer 中的第一个可见项目(假设 DataGrid 中有足够的行允许这样做)。所以我尝试了这个:
'FindVisualChild is a custom extension method that searches in the visual tree and returns
'the first element of the specified type
Dim sv = grid.FindVisualChild(Of ScrollViewer)
If sv IsNot Nothing Then sv.ScrollToEnd()
grid.ScrollIntoView(grid.SelectedItem)
首先我滚动到 DataGrid 的末尾,然后才滚动到 SelectedItem,此时 SelectedItem 显示在 DataGrid 的顶部。
我的问题是滚动到 DataGrid 的末尾效果很好,但随后滚动到所选项目并不总是有效。
我该如何解决这个问题,或者是否有任何其他替代策略可以滚动到顶部位置的特定记录?
【问题讨论】:
标签: wpf vb.net datagrid scrollviewer