When navigating around your app, it could be really helpful to maintain scroll position on various ScrollViewer controls. This also applies when your app reactivates after being suspended and shut down.
Doing it is a bit trickier than it looks since the two scroll position properties on a ScrollViewer are read-only (you need to use a method to navigate around). I can up with the following code to take care of this. Note that this could be done better by hooking directly to the LayoutAwarePage. (Note that the code as presented relies on you inheriting from LayoutAwarePage, but you could implement the same thing with any other data binding mechanism you employ.
How it works
- You maintain the scroll position in DefaultDataView. When SaveState() is called, you take the value from DefaultDataView and place it in state.
- Similarly, when LoadState() is called, you copy the value into DefaultDataView (or zero if there is no such value).
- You use the supplied dependency properties (below) to bind the ScrollViewer.
Here’s what the code looks like when saving state – note how we simply take the ScrollerPosoition key from the DefaultViewModel and copy it to the page state.
protected override void SaveState(Dictionary<string, object> pageState)
pageState["ScrollerPosition"] = DefaultViewModel["ScrollerPosition"];
Load is similar, but in the other direction:
protected override void LoadState(Object navigationParameter,
Dictionary<String, Object> pageState)
GetPageStateOrDefault("ScrollerPosition", pageState, 0.0);
Here’s the implementation for GetPageStateOrDefault() added to LayoutAwarePage:
Attached property + binding
You define the following attached property in your code (it’s a self contained class):
Finaly, in XAML, you bind this property to your DefaultViewModel:
Once all of this is done you are good – any navigation back into your page will cause the system to restore it’s position.