Before we continue, I trust that you know exactly the meaning of tombstone state in a Windows Phone 7 application. If this is not the case, simply read Yochay’s great posts on the application execution model (Part 1, Part 2, Part 3).
Every Windows Phone 7 application needs to manages tombstoning correctly to provide a better user experience and pass the application certification requirements.
When your application goes into tombstone state, it is your responsibility to save all the application and page state, so that when the page gets reloaded it can recover properly and reload the previous data. This was the user doesn’t even realizes that the application process got terminated and reloaded.
To ease the handling of the tombstone state I’ve created a simple StateManager class which helps serializing the data when going into tombstone state and deserializing the data when you get back.
How to Use StateManager?
Suppose your current page has the following data members you want to save across tombstoning:
Now all you need to do is to save them when the application goes into tombstone state and reload them when it gets back from tombstone state.
Saving the Data
The proper place for the code that saves the data resides in the OnNavigatedFrom method. In this method you should call the helper extension method SaveState for each member of the page that you want to save, passing the value and the key on which to save it:
protected override void OnNavigatedFrom(NavigationEventArgs e)
Loading the Data
The proper place for the code that loads the data when returning from tombstone state resides in OnNavigatedTo method. In this method you should call the helper extension method LoadState for each member of the page that you want to load, passing the key related to the member’s value:
protected override void OnNavigatedTo(NavigationEventArgs e)
LastPosts = this.LoadState<ObservableCollection<RssItem>>("LastPostsKey");
Posts = this.LoadState<ObservableCollection<RssItem>>("PostsKey");
Comments = this.LoadState<ObservableCollection<RssItem>>("CommentsKey");
Images = this.LoadState<ObservableCollection<ImageItem>>("ImagesKey");
Definition of StateManager
So how is the StateManager class defined? It is as simple as the following two extension methods:
Note: this code was first published as part of the “Using Pivot and Panorama Controls” lab found in the Windows Phone Training Kit for Developers, which I wrote for Microsoft.
That’s it for now,