Reputation: 4329
I am currently using the application settings class found in admam nathan's book 101 Windows Phone Apps:
public class Setting<T>
{
string name;
T value;
T defaultValue;
bool hasValue;
public Setting(string name, T defaultValue)
{
this.name = name;
this.defaultValue = defaultValue;
}
public T Value
{
get
{
//checked for cached value
if (!this.hasValue)
{
//try to get value from isolated storage
if (!IsolatedStorageSettings.ApplicationSettings.TryGetValue(this.name, out this.value))
{
//not set yet
this.value = this.defaultValue;
IsolatedStorageSettings.ApplicationSettings[this.name] = this.value;
}
this.hasValue = true;
}
return this.value;
}
set
{
//save value to isolated storage
IsolatedStorageSettings.ApplicationSettings[this.name] = value;
this.value = value;
this.hasValue = true;
}
}
public T DefaultValue
{
get { return this.defaultValue; }
}
//clear cached value;
public void ForceRefresh()
{
this.hasValue = false;
}
}
and then in a seperate class:
public static class Settings { //user settings from the settings menu
public static readonly Setting<bool> IsAerialMapStyle = new Setting<bool>("IsAerialMapStyle", false);
}
It all works fine but I can't work out how to save an array or list of length 24 to the application settings using this method.
I have this so far:
public static readonly Setting<List<bool>> ListOpened = new Setting<List<bool>>("ListOpened",....
Any help would be much appreciated!
Upvotes: 0
Views: 900
Reputation: 1734
See Using Data Contracts. You need to declare your Setting type to be serializable via [DataContract] attribute on the class definition and [DataMember] on each field (that you want to preserve). Oh, and you need System.Runtime.Serialization.
If you do not want to expose the private field values (the values are serialized to XML and might be exposed inappropriately), you could decorate the property declarations, e.g.
using System.Runtime.Serialization;
. . .
[DataContract]
public class Settings {
string Name;
. . .
[DataMember]
public T Value {
. . .
}
If your class doesn't have properties that update all the instance data, you might also have to decorate those private fields as well. It's not necessary to decorate both the public property and the corresponding private field.
Oh, and all the types T that you wrap this class around have to be serializable, too. The primitive types are, but user-defined classes (and maybe some CLR types?) would not be.
Upvotes: 1
Reputation: 3217
Unfortunately, AFAIK, you cannot store it in ApplicationSettings
as a single key value
dictionary entry. You can only store built-in data types(int, long, bool, string..). To save a list like this, you'll have to serialize the object into memory, or use the SQLCE database to store the values (Mango).
Upvotes: 0