我有一个包含许多项的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的底部,然后再滚动到所选项,这时所选项会显示在DataGrid的顶部。
我的问题是,滚动到DataGrid底部可以正常工作,但随后滚动到所选项并不总是有效。
如何解决这个问题,或者是否有其他替代策略可以将特定记录滚动到顶部位置?