2011-11-25 47 views
1
我目前使用admam Nathan的书101的Windows Phone应用程序中发现的应用程序设置类

数组的applicationSettings:保存列表或使用自定义类

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; 
    } 
} 

,然后在一个单独的类:

公共静态类设置 {从设置菜单 //用户设置

public static readonly Setting<bool> IsAerialMapStyle = new Setting<bool>("IsAerialMapStyle", false); 

}

这一切工作正常,但我不能解决如何将数组或长度为24的列表保存到使用此方法的应用程序设置。

我有这个至今:

public static readonly Setting<List<bool>> ListOpened = new Setting<List<bool>>("ListOpened",.... 

任何帮助,将不胜感激!

回答

1

参见Using Data Contracts。 您需要声明您的设置类型可通过类定义上的[DataContract]属性和每个字段(您要保留的)上的[DataMember]进行序列化。哦,你需要System.Runtime.Serialization。

如果您不想公开私有字段值(值被序列化为XML并且可能会暴露不当),您可以修饰属性声明,例如,

using System.Runtime.Serialization; 
. . . 
[DataContract] 
public class Settings { 
    string Name; 
    . . . 
    [DataMember] 
    public T Value { 
    . . . 
    } 

如果您的类没有更新所有实例数据的属性,那么您可能还必须修饰这些私有字段。没有必要装饰公共财产和相应的私人领域。

哦,你包装这个类的所有类型T也必须是可序列化的。原始类型是,但用户定义的类(也许一些CLR类型?)不会。

0

不幸的是,AFAIK,不能将它作为单个key value字典条目存储在ApplicationSettings中。你只能存储内置的数据类型(int,long,bool,string ..)。为了保存这样的列表,您必须将对象序列化到内存中,或使用SQLCE数据库来存储值(Mango)。

相关问题