Page State–Step by Step

Windows Phone Tutorial

The Windows Phone life cycle is not terribly complicated, but it can be the source of some LifeCycle  confusion, and managing the life-cycle can be intimidating to new Windows Phone programmers.  This posting will review the basic life-cycle of a Windows Phone application and will show you what you need to do to preserve state and give your users a rewarding phone experience.

Reviewing the Life Cycle

When your application is launched (e.g., from the start menu) the Application Launching event is fired. You can hook this event in App.xaml.cs in the Application_Launching event handler, as described in yesterday’s posting on Fast Application Switching.

Once the application is started, and every time the user navigates to your page, you  will receive the OnNavigatedTo method, after which your page will be in the Running state.

If the user starts a new application your application receives the Application Deactivated event and is put in the Dormant state.  If the phone runs low on memory, your application may be Tombstoned.

From either Tombstoned or Dormant your application may be terminated or it may be restored.  What we care about right now is what happens when your application is restored.

If your application is Dormant, you not only don’t have to take any action when you are restored, you don’t want to take any action; all your state was preserved when you were dormant, and you are ready to go.

If on the other hand, your application was tombstoned, then you do want to restore your page state when you return so that it appears to the user that your application was running (or at least dormant) while it was switched away.

Managing Page State

The best way to see how to manage Page State is to build a small application.  Open Visual Studio and create a new Windows Phone application and on the main page add a prompt and a TextBox for the user’s name, and a CheckBox for whether the user is a Geek, as shown in the following code,

<Grid
    x:Name="ContentPanel"
    Grid.Row="1"
    Margin="12,0,12,0">
    <Grid.RowDefinitions>
        <RowDefinition
            Height="1*" />
        <RowDefinition
            Height="1*" />
        <RowDefinition
            Height="4*" />
    </Grid.RowDefinitions>
    <StackPanel
        Grid.Row="0"
        VerticalAlignment="Stretch"
        HorizontalAlignment="Stretch"
        Orientation="Horizontal">
        <TextBlock
            Text="Full Name:"
            Margin="5"
            HorizontalAlignment="Right"
            VerticalAlignment="Center" />
        <TextBox Name="FullName" Text="" Margin="5"
                 Width="300"
            HorizontalAlignment="Right"
            VerticalAlignment="Center" />
    </StackPanel>
    <CheckBox
        Name="Geek"
        Content="Geek?"
        IsChecked="True"
        Grid.Row="1"
        VerticalAlignment="Center" />

</Grid>

Binding the Controls

Right now the CheckBox and TextBox have hardcoded values. We’d prefer to bind these values to an object.   Create MainPageViewModel.cs and have it implement INotifyPropertyChanged,

public class MainPageViewModel : INotifyPropertyChanged
{

    private string _userName;
    public string UserName
    {
        get { return _userName; }
        set
        {
            _userName = value;
            NotifyPropertyChanged( "UserName" );
        }
    }

    private bool _isGeek;
    public bool IsGeek
    {
        get { return _isGeek; }
        set
        {
            _isGeek = value;
            NotifyPropertyChanged( "IsGeek" );
        }

    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged( string propName )
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(
                this,
                new PropertyChangedEventArgs( propName ) );
        }
    }
}

Return to the Xaml and change the text property of the TextBox and the content property of the  CheckBox to databind to your new ViewModel,

<TextBox
    Name="FullName"
    Text="{Binding UserName, Mode=TwoWay}"
    Margin="5"
    Width="300"
    HorizontalAlignment="Right"
    VerticalAlignment="Center" />

  <CheckBox
     Name="Geek"
     Content="{Binding IsGeek, Mode=TwoWay}"
     IsChecked="True"
     Grid.Row="1"
     VerticalAlignment="Center" />

Add attributes to make the class DataContract Serializable

So far this is straight data-binding, nothing special.  Because you’ll want to save an instance of the MainPageViewModel in Page State, however, you must make it DataContract serializable. You do that with attributes.

Add a reference to the System.Runtime.Serialization library.

Return to the MainPageViewModel.cs file and add the [DataContract] attribute to the class and add [DataMember] attributes to all the properties that you want serialized,

 [DataContract]
 public class MainPageViewModel : INotifyPropertyChanged
 {

     private string _userName;

     [DataMember]
     public string UserName
     {
        //...
     }

     private bool _isGeek;

     [DataMember]
     public bool IsGeek
     {
        //...
     }

Track the state

The final step is to add a flag to the MainPage class to track whether you are seeing a new instance of the page or a restored instance. It is this flag (_isNewPageInstance) that will ensure that your page is efficient. If you return to the page after being tombstoned you want this flag to be true, but if you return after being dormant you want it to be false.

MainPageViewModel _vm;
bool _isNewPageInstance = false;

[ Note that we also added a member variable to hold the MainPageViewModel instance. ]

The Page Logic

Begin by initializing the flag to false (as shown) but setting the flag to true in your constructor.

public MainPage()
{
    InitializeComponent();
    _isNewPageInstance = true;
}

Override the OnNavigatedFrom method and save the page state unless the navigation mode is Back, in which case the page is begin discarded and there is no reason to save state,

protected override void OnNavigatedFrom(
    System.Windows.Navigation.NavigationEventArgs e )
{
    if (e.NavigationMode !=
          System.Windows.Navigation.NavigationMode.Back)
    {
        State["MainPageViewModel"] = _vm;
    }
}

Next, override the OnNavigatedTo method. Here is where that flag comes into play.  You might be coming to this page under a number of different conditions. Let’s consider three primary cases:

  • This is your first time on the page – in that case the constructor will be called, and the flag will be true, but there will be nothing in the State dictionary
  • You are returning to this page from being tombstoned – in this case the flag will be true.  When you return from tombstoning the constructor is called and the flag is set to true.
  • You are returning from the application being Dormant – in this case state was preserved and so the flag will be false.

The reason the flag is false when you return from the Dormant state is that we set it to false at the end of OnNavigatedTo (as you’ll see in a moment) and that state is preserved when the page is Dormant. Returning from Dormant does not call the constructor.

The critical difference is that after tombstoning the flag is true (indicating you should go get the state you saved in the Page State dictionary) and after being dormant the flag is false (indicating that you do not need to restore state).

Here’s the override of OnNavigatedTo,

protected override void OnNavigatedTo(
    System.Windows.Navigation.NavigationEventArgs e )
{
    if (_isNewPageInstance)
    {
        if (_vm == null)
        {
            if (State.ContainsKey( "MainPageViewModel"))
            {
                MessageBox.Show( "Retrieving state..." );
                _vm = State["MainPageViewModel"]
                                   as MainPageViewModel;
            }
            else
            {
                _vm = new MainPageViewModel();
            }
        }
        DataContext = _vm;
    }
    _isNewPageInstance = false;
}

The State Machine

The first time you get here (e.g., when the application is launched) the first if statement evaluates to true (_isNewPageInstance was set to true in the constructor).  The instance of MainPageViewModel will be null but the State object will not contain anything and so you’ll create a new instance of MainPageViewModel.

If you get here from a dormant state then the first if statement will fail ( _isNewPageInstance == false) and you’ll fall through changing nothing and not taking any time to restore state, as state is already intact.  This is a very good thing; no time is wasted restoring state.

Finally, if you get here from being tombstoned the first if statement will evaluate true (remember that you go through the constructor) and the vm will be null, but this time the Page State object will have the MainPageViewModel object and so you can retrieve it.

Run the program and note that the message box does not come up.  Next, stop the application and right click on the project, and choose Properties.  Select the Debug tab and check the checkbox that says Tombstone upon deactivation while debugging.  Run the application and note that the message box does indicate that this time state is being restored.

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 Essentials, Mango, Mini-Tutorial, Patterns & Skills, WindowsPhone and tagged . Bookmark the permalink.

9 Responses to Page State–Step by Step

  1. Pingback: Lifecycle of page

  2. Very good site you have here but I was wanting to know
    if you knew of any forums that cover the same topics talked
    about here? I’d really love to be a part of community where I can get feed-back from
    other knowledgeable people that share the same interest.

    If you have any recommendations, please let me know.
    Thanks a lot!

  3. I was suggested this website by my cousin. I am
    not sure whether this post is written by him as nobody else know such detailed about my difficulty.
    You are incredible! Thanks!

    My website – marketing Conference

  4. Pablo says:

    Very Interesting!!!!!

  5. Anonymous says:

    Great post, I’ll definitely be putting this info to good use in my WP7 app. Currently it creates an instance of the VM every time the page’s constructor is called. Which I guess isn’t too bad since I’m still getting the benefit of the Dormant to active maintaining state and there by skipping the ctor. However, thanks to your article I’ll cut down on the hits to isolated storage, which should speed up performance a fair bit.

  6. Alexandra says:

    If the app is Dormant and a user changes a theme, then returns to the app, it does not change colors (even if colors were set like {StaticResource PhoneForegroundBrush}, etc). What’s the right way to fix it?

  7. Pingback: Page State–Step by Step | Jesse Liberty » Saintchubs.com

  8. Pingback: Windows Phone: Page State – Step by Step – www.nalli.net

Leave a Reply

Your email address will not be published.