Last Updated: February 25, 2016
·
1.111K
· aviatrix

Helper for working with settings in windows phone 7/8

I got tired of writing constant checks and whatnot to make my settings work.
So i wrote this simple helper to ease my work.
You need Json.NET from nuget to make this work.

It saves the settings in the internal storage settings area as a json objects,

here's sample usage :

SettingsHelper.SetOption("ColorToUse", Color.ToString())
SettingsHelper.GetOption<string>("ColorToUse")

Hope this saves you some headaches :)

public static class SettingsHelper
{
    public static void SetOption<T>(string key, T value)
    {
        if (IsolatedStorageSettings.ApplicationSettings.Count(x => x.Key == key) == 0)
        {
            IsolatedStorageSettings.ApplicationSettings.Add(key, JsonConvert.SerializeObject(value));
        }
        else
        {
            IsolatedStorageSettings.ApplicationSettings[key] = JsonConvert.SerializeObject(value);
        }
        IsolatedStorageSettings.ApplicationSettings.Save();
    }

    public static T GetOption<T>(string key)
    {
        if (IsolatedStorageSettings.ApplicationSettings.Count(x => x.Key == key) == 0)
        {
            return default(T);
        }
        else
        {
            return JsonConvert.DeserializeObject<T>(IsolatedStorageSettings.ApplicationSettings[key].ToString());
        }
    }
}