Many times in our Windows Phone 7 applications we are using some settings to provide high quality and user flexible/friendly apps. To reach this we should use IsolatedStorageSettings class which contains ApplicationSettings dictionary based on string as key and object as value. To prevent writing code responsible for retrieving and casting values from this dictionary in many places I’ve created class called SettingsProvides with two generic methods like below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | public class SettingsProvider { ... #region internal private static void SetValue(string key, T value) { if (IsolatedStorageSettings.ApplicationSettings.Contains(key)) { IsolatedStorageSettings.ApplicationSettings[key] = value; } else { IsolatedStorageSettings.ApplicationSettings.Add(key, value); } } private static T GetValueOrDefault(string key, T defaultValue) { if (IsolatedStorageSettings.ApplicationSettings.Contains(key)) { return (T)IsolatedStorageSettings.ApplicationSettings[key]; } else { IsolatedStorageSettings.ApplicationSettings.Add(key, defaultValue); return defaultValue; } } #endregion } |
Thanks to this I can provide to my application set of strongly typed properties for example like those:
1 2 3 4 5 | public string UserName { get { return GetValueOrDefault("UserName", ""); } set { SetValue("UserName", value); } } |
I hope that this small code snippet will help you easier create and use application settings feature in your Windows Phone apps