silverlight save settings
April 6, 2010 at 6:19 PM
—
dsoltesz
There are lots of time when you want to be able to store user settings in between sessions of your application. I found that using Isoloated Storage makes this very easy. I created a helper class to do just this.
IsolatedStorageManager.cs
using System.IO.IsolatedStorage;
namespace MyApp.Utilities
{
public static class IsolatedStorageManager
{
/// <summary>
/// Save property and value into isolated storage
/// </summary>
/// <param name="value">value to store</param>
/// <param name="name">name of property</param>
public static void SaveIntoIsolatedStorage(object value, string name)
{
IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings;
//If settings have never been saved, then we have to add appsetting first
if (!appSettings.Contains(name))
{
appSettings.Add(name, null);
}
//store page user is currently on for when they come back in
appSettings[name] = value;
}
public static bool Contains(string name)
{
IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings;
return appSettings.Contains(name);
}
/// <summary>
/// Remove property value from isolated storage
/// </summary>
/// <param name="name">name of property</param>
public static void Remove(string name)
{
IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings;
//If settings have been saved, then we remove since the user wants to select a new queue/page
if (appSettings.Contains(name))
{
appSettings.Remove(name);
}
}
/// <summary>
/// Removes all properties stored in isolated storage
/// </summary>
public static void RemoveAll()
{
IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings;
appSettings.Clear();
}
/// <summary>
/// Retrieve setting that was stored in Isolated Storage
/// </summary>
/// <param name="name">name of the property to retrieve</param>
/// <returns></returns>
public static object LoadFromIsolatedStorage(string name)
{
IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings;
if (appSettings.Contains(name))
{
return appSettings[name];
}
return null;
}
}
}
Now when we want to save a user setting or retrieve a user setting we can simple use our helper class.
Example: I wanted to remember the last page the user was on and automatically navigate the user to that page when they returned. Whenever a user navigated to a page I would simple store the name of the current page
IsolatedStorageManager .SaveIntoIsolatedStorage(pageName, Constants.CURRENT_PAGE);
Now when the user leaves your application and returns, we can check to see what page they were on before and return them to that page.
if (IsolatedStorageManager.Contains(Constants.CURRENT_PAGE)) //user was here before
{
NavigateToPage((string)IsolatedStorageManager.LoadFromIsolatedStorage(Constants.CURRENT_PAGE));
}
else
{
NavigateToPage("Home");
}