I have a Listview with 20 items in it. I want to scroll the Listview programmatically.
ListView?.ScrollIntoView(ListView.Items[0])
will scroll the listview to the first item.
ListView?.ScrollIntoView(ListView.Items.Count - 1)
will scroll the listview to the bottom of the page.
However, I am unable to use the same function to scroll the listview to an item in middle.
Eg: ListView?.ScrollIntoView(ListView.Items[5])
should scroll and take me to the 5th item of the list. But instead its taking me to the first item of the list.
Would be great if this behaviour can be achieved with some workaround?
I solve this like:
And the GetScrollViewer method:
credits to the owner of the code
I think what you are looking for is a method to actually scroll an element to the top of the
ListView
.In this post, I created an extension method that scrolls to a particular element within a
ScrollViewer
.The idea is the same in your case.
You need to first find the
ScrollViewer
instance within yourListView
, then the actual item to scroll to, that is, aListViewItem
.Here is an extension method to get the
ScrollViewer
.Once I get the
ScrollViewer
instance, I have created two more extension methods to scroll to an item based on its index or attached object respectively. SinceListView
andGridView
are sharing the same base classListViewBase
. These two extension methods should also work forGridView
.Update
Basically, the methods will first find the item, if it's already rendered, then scroll to it right away. If the item is
null
, it means the virtualization is on and the item has yet to be realized. So to realize the item first, callScrollIntoViewAsync
(task-based method to wrap the built-inScrollIntoView
, same asChangeViewAsync
, which offers much cleaner code), calculate the position and save it. Since now I know the position to scroll to, I need to first scroll the item all the way back to its previous position instantly (i.e. without animation), and then finally scroll to the desired position with animation.A simpler approach, but without animation
You can also use the new overload of
ScrollIntoView
by specifying the second parameter to make sure the item is aligned on the top edge; however, doing so doesn't have the smooth scrolling transition in my previous extension methods.ScrollIntoView just brings the item into the view, period, it does not scroll to a row.
If you call it on a member and it is below the bottom of the visible list it scrolls down until the the item is the last member in the visible list.
If you call it on a member and it is above the top of the list it scrolls up until the the item is the first member in the list.
If you call it on a member and it is currently visible it does no operation at all.