Life Cycle: Page State Management

Windows Phone From Scratch #29

In previous postings, I’ve discussed the Life Cycle of a Windows Phone application and SavingState in that context noted the requirement to maintain the page’s state when the user navigates away (so that state can be restored when the user returns)

There are a few practical elements to state management, so let’s devote a few of these mini-tutorials to the exact mechanisms involved

To start, let’s examine the scenario where the user is on a first page, fills in some data, and then navigates to a second page.  For whatever reason, the user clicks the back button on the phone and is returned to the first page.  At this point the user expects to see the data already filled in to be there, ready for editing. 

If the user hits the back button and the fields already created are now empty the application is in a state technically  referred to as “sucks.”

To prevent this, you will want to store the values in a State dictionary and restore those values if the user hits the back button.  Fortunately, this is fairly easy to do, though you have to be a bit careful when restoring. 

To see this, create a new application with two pages: Mainpage.xaml and Page2.xaml.  On MainPage.xaml create a few text input fields and a button, on page 2 put anything you like.  You can see the MainPage.xaml I created in the illustration above.

Saving and Restoring State

Saving the state is pretty straightforward.

As noted in the earlier article, when you are navigating away form the page the OnNavigatedFrom event is raised.  Each page has an individual pre-defined State dictionary, to which you can save the state of your controls,

 protected override void  OnNavigatedFrom(
     System.Windows.Navigation.NavigationEventArgs e)
 {
    State["Name"] = FullName.Text;
    State["eMail"] = eMail.Text;
    State["Phone"] = Phone.Text;
    base.OnNavigatedFrom(e);
 }

 

Restoring is just a bit trickier as you have to make sure that the value you attempt to retrieve from the dictionary actually exists.  For this, I like to use the TryGetValue method, as it does not throw an exception.  It takes two values and returns a boolean.  The first parameter is the name of the “key” you are looking for. The second is an out parameter that will hold the value if found. The returned value is a boolean, true if the key was found, false if it was not.

Remembering that the dictionary holds objects, we search for the key and if it is found we call ToString on the values obtained before writing them back to the control,

Here is the complete code behind page,

using System;
using System.Windows;
using Microsoft.Phone.Controls;

namespace PageState
{
   public partial class MainPage : PhoneApplicationPage
   {
      // Constructor
      public MainPage()
      {
         InitializeComponent();
         GoToPage2.Click += GoToPage2_Click;
      }

      void GoToPage2_Click( object sender, RoutedEventArgs e )
      {
         NavigationService.Navigate( 
            new Uri( "/Page2.xaml", UriKind.Relative ) );
      }
      protected override void OnNavigatedFrom(
         System.Windows.Navigation.NavigationEventArgs e )
      {
         State["Name"] = FullName.Text;
         State["eMail"] = eMail.Text;
         State["Phone"] = Phone.Text;
         base.OnNavigatedFrom( e );
      }
      protected override void OnNavigatedTo( 
         System.Windows.Navigation.NavigationEventArgs e )
      {
         base.OnNavigatedTo( e );
         object val;

         if ( State.TryGetValue( "Name", out val ) )
            FullName.Text = val.ToString();
         if ( State.TryGetValue( "eMail", out val ) )
            eMail.Text = val.ToString();
         if ( State.TryGetValue( "Phone", out val ) )
            Phone.Text = val.ToString();
      }
   }
}
Share

About Jesse Liberty

Jesse Liberty is an independent consultant and programmer with three decades of experience writing and delivering software projects. He is the author of 2 dozen books and multiple Pluralsight courses, and has been a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Xamarin Certified Mobile Developer and a Xamarin MVP, Microsoft MVP and Telerik MVP.
This entry was posted in Patterns & Skills. Bookmark the permalink.

2 Responses to Life Cycle: Page State Management

  1. Pingback: Windows Phone 7 Application Life Cycle: Page State Management | www.nalli.net

  2. Pingback: Tweets that mention Life Cycle: Page State Management | Jesse Liberty -- Topsy.com

Leave a Reply

Your email address will not be published.