I have a DataGrid with many items and I need to programmatically scroll to the SelectedItem
. I have searched on StackOverflow and Google, and it seems the solution is ScrollIntoView, as follows:
grid.ScrollIntoView(grid.SelectedItem)
which scrolls the DataGrid up or down until the selected item is in focus. However, depending on the current scroll position relative to the selected item, the selected item may end up being the last visible item in the DataGrid's ScrollViewer. I want that the selected item will be the first visible item in the ScrollViewer (assuming there are enough rows in the DataGrid to allow this). So I tried this:
'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)
First I scroll to the end of the DataGrid and only then do I scroll to the SelectedItem, at which point the SelectedItem is shown at the top of the DataGrid.
My problem is that scrolling to the end of the DataGrid works well, but subsequently scrolling to the selected item doesn't always work.
How can I resolve this issue, or is there any other alternative strategy for scrolling to a specific record in the top position?
The accepted answer to this other question shows a different approach to get the first/last visible row of such a grid. You could find out the index of your row and directly scroll there or scroll down row by row until the first visible row matches.