Remember ScrollViewer Position

Often in Windows 8 apps the user will be presented with long horizontal groups of content. After having navigated to these items, and then returning to the original page there is no built in functionality to remember where in the list that the user scrolled to.

Creating this feature is relatively quick:

  1. Whenever the user leaves the page, remember the current scroll position.
  2. Whenever the user navigates back to the page, retrieve the previous scroll position
  3. When all your content is loaded, scroll to the previous position
// Step 1
private double? horizontalOffsetState;

protected override void SaveState(Dictionary<string, object> pageState)
{
base.SaveState(pageState);

var myScrollViewer = … // your scroll viewer
var offset = myScrollViewer.HorizontalOffset;

pageState["horizontalOffset"] = offset;
}

// Step 2
protected override void LoadState(object navigationParameter,Dictionary<string, object> pageState)
{
base.LoadState(navigationParameter, pageState);

if (pageState != null)
{
horizontalOffsetState = (double) pageState["horizontalOffset"];
}
}

// step 3 - put in constructor or loadstate/navigatedTo
this.Loaded += (sender, args) =>
{
var myScrollViewer = … // your scroll viewer
if (horizontalOffsetState.HasValue)
{
myScrollViewer.ScrollToHorizontalOffset(horizontalOffsetState.Value);
}

};