WP7: PhoneApplicationService.Current.State made easy

UPDATE 7 NOV 2011: Have a look at this post: WP7: Northern Lights WP7 Toolkit v0.0.1 for the latest version of this code example.

I was reading “Programming Windows Phone 7”, a free Microsoft book (as PDF) from Charles Petzold and came across some code on why and how to access the PhoneApplicationService.Current.State (chapter 6, “Page State” paragraph) and thought about writing the following code to improve the usability.
Hope you like it:

    public class StateManager
    {
        private static PhoneApplicationService appService = PhoneApplicationService.Current;

        public static void Set<T>(string name, T value)
        {
            appService.State[name] = value;
        }

        public static T Get<T>(string name)
        {
            T result = default(T);

            if (appService.State.ContainsKey(name))
            {
                result = (T)appService.State[name];
            }

            return result;
        }
    }

It can then be invoked as follows:

Set a value

StateManager.Set<MyObject>("MyApplicationObject", obj);

Get a value

MyObject obj = StateManager.Get<MyObject>("MyApplicationObject");

Hope you like it.

5 Comments.

  1. I needed this! Thanks tons! 😯

  2. This seems to be returning a zero value, when passing a TimeSpan.
    I am setting the value as such:
    OnNavigatingFrom(…)
    {
    StateManager.Set(“Span”, _span);
    }

    and in the Page’s constructor, getting the values as such:
    _span = StateManager.Get(“Span”);

    I wonder, should these operations be instead in thea Applxaml.cs, in Application_Activated methods instead?

    • Look at my library Northernlights. It has an improved version of the StateManager called StateVariables. The problem you are having is probably caused by the fact that TimeSpan might not be serializable?! State variables can only be serializable objects.

  3. What is the benefit of using “PhoneApplicationService.Current.State” compared to simply using static variables in App.xaml.cs ?

    • The static variable in App.xaml.cs will be reset with its default value when the app is resumed (returns from tombstoned state) where as the PhoneApplicationService.Current.State will load the last set value for its property.