WinRT: Static Local Storage Settings
Application settings are useful for quickly storing some value for later runs of the application. A great example of this is storing the last selected item id so that the next time the user runs the app we can start by loading the last viewed item. Another scenario is for searching when our application is in a closed state. Our search code may require a selected item. Using application settings enables us to quickly store anything we need between runs of our application. For working with application settings in WinRT we have the ApplicationDataContainer class. It represents a container for creating, deleting and finding settings in a dictionary like structure. The LocalStorage class shows a static example of saving and loading a simple item ID. By making the class static we can conveniently access it anywhere else in our application in code like:
// save last item
LocalStorage.SaveLastItemId(id);
// load last item
string itemId = LocalStorage.LoadLastItemId();
// public class for getting and setting some application settings
public sealed class LocalStorage
{
public static LocalStorage _localStorage = new LocalStorage();
ApplicationDataContainer _localSettings;
public ApplicationDataContainer LocalSettings
{
get
{
if (_localSettings == null)
{
_localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
}
return _localSettings;
}
set
{
_localSettings = value;
}
}
public LocalStorage()
{
}
public static void SaveLastItemId(string id)
{
if (!_localStorage.LocalSettings.Containers.ContainsKey("AppSettings"))
{
\_localStorage.LocalSettings = \_localStorage.LocalSettings.CreateContainer("AppSettings", Windows.Storage.ApplicationDataCreateDisposition.Always);
}
if (_localStorage.LocalSettings.Containers.ContainsKey("AppSettings"))
{
if (_localStorage.LocalSettings.Containers["AppSettings"].Values.ContainsKey("LastItemID"))
_localStorage.LocalSettings.Containers["AppSettings"].Values["LastItemID"] = lastStudioId;
else
_localStorage.LocalSettings.Containers["AppSettings"].Values.Add("LastItemID", lastStudioId);
}
}
public static string LoadLastItemId()
{
string lastItemId = "";
if (_localStorage.LocalSettings.Containers.ContainsKey("AppSettings"))
{
if (_localStorage.LocalSettings.Containers["AppSettings"].Values.ContainsKey("LastItemID"))
lastItemId = _localStorage.LocalSettings.Containers["AppSettings"].Values["LastItemID"].ToString();
}
return lastItemId;
}
}