How to restore scroll position of the GridView when navigating back.
When developing WinRT applications which utilize GridView or ListView controls you'd come to the situation when navigating back to a page, you need to restore the scroll position of aforementioned controls. The solution that you can employ in this case is to get access to the ScrollView control which is a visual child of these controls and then remember a current scroll offset. In order to find the ScrollView you can use the FindVisualChild method that you can get from this msdn page. You can call to this method in your page's Loaded event handler:
void ItemsPage_Loaded(object sender, RoutedEventArgs e)
{
this.gridScrollViewer = FindVisualChild<ScrollViewer>(this.itemGridView);
this.gridScrollViewer.ScrollToHorizontalOffset(App.ScrollOffset);
}
What's left to do is to remember the scroll offset when you navigate away from this page:
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
App.ScrollOffset = gridScrollViewer.HorizontalOffset;
base.OnNavigatedFrom(e);
}
Happy Windows 8 coding!
Comments
Anonymous
September 10, 2012
What is App.ScrollOffset ?Anonymous
September 10, 2012
Hi Erik, The App.ScrollOffset is just global variable/property of a double type. -AlexAnonymous
October 13, 2014
Thanks Alex for the nice and easy to understand post.Anonymous
January 22, 2015
This doesn't work all the time for WP8.1