The IsolatedStorageSettings is a place to store Key/Value pairs of data.
So let's say that my application used the Microsoft Ad control, but I wanted to be nice and give the user the ability to turn the ads on and off.
On my Settings screen, I would have a checkbox(AdsCheckbox) for allowing the ads. In code, I would save the value by doing this...
var settings = IsolatedStorageSettings.ApplicationSettings;
if (settings.Contains("AllowAds"))
settings["AllowAds"] = AdsCheckbox.IsChecked.Value;
else
settings.Add("AllowAds", AdsCheckbox.IsChecked.Value);
settings.Save();
If you will notice, the ApplicationSettings object does have a method that allows you to check to see if the key already exists in the Settings. An exception will be thrown if you try to add a key that already exists, so it's necessary to do this check before assigning a value.
Also, as you can see, it's very easy to get the value out of the settings...
// when the form opens, I want to set the Checkbox to being checked
// or unchecked depending on the setting
var settings = IsolatedStorageSettings.ApplicationSettings;
if (settings.Contains("AllowAds"))
AdsCheckbox.IsChecked = bool.Parse(settings["AllowAds"].ToString());
However, the IsolatedStorageSettings class isn't only for simply datatypes. It can also store your custom class objects.
Employee class
public class Employee
{
public string FullName { get; set; }
public decimal Salary { get; set; }
}
Then on my form, I have a button to save an instance of the Employee class to the IsolatedStorageSettings...
private void btnSave_Click(object sender, RoutedEventArgs e)
{
var settings = IsolatedStorageSettings.ApplicationSettings;
Employee emp = new Employee()
{
FullName = "John Doe",
Salary = 250000
};
settings.Add("Employee1", emp);
settings.Save();
}
I also have a button that will load the object from the IsolatedStorageSettings...
private void btnLoad_Click(object sender, RoutedEventArgs e)
{
var settings = IsolatedStorageSettings.ApplicationSettings;
Employee emp;
if (settings.TryGetValue<Employee>("Employee1", out emp))
{
MessageBox.Show(string.Format("Full Name: {0}\nSalary: {1:c}", emp.FullName, emp.Salary));
}
}
Notice that the IsolatedStorageSettings.ApplicationSettings class also has the TryGetValue method. This method behaves exactly like the TryParse methods of the .Net datatypes. It will return a boolean specifying whether the key was found and whether the conversion from object --> Employee was successful. If it's successful, it will return the instance as the out parameter.
After running the application, clicking the Save button, then clicking the Load button, we will get this message box...
11-7-2010 2-55-20 PM.png (8.46K)
Number of downloads: 4





MultiQuote



|