Tag Archives: beta 2

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.