2011-11-25 44 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)。

相關問題