2011-05-20 43 views
5

我在使用WP7獨立存儲和應用程序設置時遇到很大問題。 我一直在使用Adam Nathan的101 Windows Phone 7應用程序卷1中的代碼作爲基礎。獨立存儲應用程序設置在應用程序退出後不持續

我有一個設置頁面,其中的值可以改變,而應用程序仍在運行,這些仍然活躍,它的一切都完美。但是,一旦應用程序在我的開發人員手機上退出,這些程序就會丟失,並且應用程序將使用默認設置重新啓動。

我不知道爲什麼這些值不會持續。任何幫助將非常感激。

這是我的代碼,它來自adam nathan的新書。我在twitter上給他發了一條消息,他說它使用的是不可序列化的數據類型。我看着這個,但我只使用double和bool值。

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

進一步發展:

我收到退出應用程序這個錯誤:

型 'System.IO.IsolatedStorage.IsolatedStorageException' 的第一次機會異常出現在mscorlib.dll


發現錯誤:我是個白癡,並且忽略了一個感嘆號!來自trygetvalue部分。

+1

您能告訴我們您的隔離存儲代碼嗎? – keyboardP 2011-05-20 01:01:30

+0

完成了,已經在上面加了,謝謝 – 2011-05-20 11:37:18

+0

關於異常,請檢查一下這個線程:http://forums.create.msdn.com/forums/t/65662.aspx?PageIndex=1 – keyboardP 2011-05-20 13:55:02

回答

8

您可以發佈您的存儲代碼,以便我們可以看到究竟發生了什麼?在該代碼的由於缺少,這裏是我用來保存設置到本地存儲的代碼:

IsolatedStorageSettings isoStoreSettings = IsolatedStorageSettings.ApplicationSettings; 
if (isoStoreSettings.Contains(key)) 
{ 
    isoStoreSettings[key] = value; 
} 
else 
{ 
    isoStoreSettings.Add(key, value); 
} 
isoStoreSettings.Save(); 

我的猜測是,你缺少承諾物化獨立存儲的變化,以獨立存儲設置,而不是最後一行只是把它們留在記憶中。如果情況並非如此,請使用代碼編輯您的帖子,以便我們提供幫助。

+1

應用程序關閉時應該自動保留更改,但我總是也自己也自己調用Save()。 – 2011-05-20 08:04:11

+0

感謝您的回答,我已經添加了我的代碼 – 2011-05-20 11:35:48

+0

非常感謝Jared,我也犯了同樣的錯誤。 – 2013-02-26 17:42:26