Is there a best practice for handling tombstoning and back key properly?
As it is stated in the MSDN docu you should save transient data in the OnNavigatedFrom
method. Ok, so the code for saving states when tombstoning is clear.
But now if you press the back key the OnNavigatedFrom
method is also called and if you don't add extra checks, you will first save states into the dictionary and shortly after that the page will be destroyed. And so will the PhoneApplicationPage.State dictionary. So the saving code is completely wasted CPU, disk and battery time.
This is what I've done to prevent it:
protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
{
// when navigating back
if (e.NavigationMode == System.Windows.Navigation.NavigationMode.Back)
{
backKeyPressed = true;
}
}
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
if (backKeyPressed)
{
// Don't save states on back key!
backKeyPressed = false; // set it anyway
return;
}
// Tombstoning
// save objects
this.SaveState("text", someText);
...
}
As a reminder: OnNavigatingFrom
will only be called when navigating away/back from the page but not when app gets tombstoned.
Side note: Shown code covers only pages that can only navigate back. Thats why I added backKeypressed to OnNavigatingFrom
. You need extra checks if the page can navigate to another page.
- Is there a better way to do this for every page you create?
- Now do I really have to add the
backKeyPressed
variable and check on every page I create? - Shouldn't the framework provide something for us developer so we don't have to worry much about this?
What are your thoughts about this?
EDIT:
Updated question the make it clearer.