2014-04-30 42 views
0

我的目標是檢索應用程序關閉時上次存儲的計數器的值。 即我將計數器值存儲在獨立存儲中。如果計數器的值爲5,並且應用程序已關閉並重新啓動,則應該能夠檢索5. 爲此,我已經編寫了下面的代碼,但是我無法解決這個問題。在IsolatedStorageSettings中聲明密鑰

IsolatedStorageSettings isoStoreSettings = IsolatedStorageSettings.ApplicationSettings; 
int count=0; 
isoStoreSettings["flag"]; 
if (isoStoreSettings["flag"]!="set") 
{     
    isoStoreSettings["count"] = count; 
    isoStoreSettings["flag"] = "set"; 
} 


count = isoStorageSettings["count"]; //using the value of count stored previously 

//some code which updates the count variable 

isoStorageSettings["count"]=count; 

與此代碼的問題是isolatedstorage關鍵的那個聲明是現在允許的,我們必須一定值分配給關鍵 但如果我將值分配給該鍵,它會重新初始化密鑰每次應用程序開始。因此,如果有人可以解決這個問題,請幫助 即使有其他替代方案爲我的目標也請分享。在Add方法

+0

你在哪裏使用此碼?什麼是國旗? – Romasz

回答

0

如果你希望你的count每次加載應用啓動然後將您的代碼放入App.xaml.cs中的Application_Launching事件中:

// declare static variable which you will be able to access from anywhere 
public static int count; 

private void Application_Launching(object sender, LaunchingEventArgs e) 
{ 
    IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings; 
    if (settings.Contains("count")) count = (int)settings["count"]; 
    else count = 0; 
} 

在Clising事件 - 保存您的變量:

private void Application_Closing(object sender, ClosingEventArgs e) 
{ 
    IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings; 
    if (settings.Contains("count")) settings["count"] = count; 
    else settings.Add("count", count); 
    settings.Save(); 
} 

在你的代碼的任何地方,你應該能夠訪問你的變量是這樣的:

int myVariable = App.count; 
App.count++; 
// and so on 

注意,你也可以考慮一下ActivatedDeactivated事件 - 欲瞭解更多信息,請閱讀MSDN

我也不知道flag假設要做什麼,但上面的代碼應該保存你的變量就好了。

+0

此代碼爲我工作。它完全做我想要的。 –

0

使用更新的計數值如下圖所示:

IsolatedStorageSettings isolatedStorageSettingsCount = IsolatedStorageSettings.ApplicationSettings; 
if (isolatedStorageSettingsCount.Contains("count")) 
      { 
       isolatedStorageSettingsCount.Remove("count"); 
       isolatedStorageSettingsCount.Add("count",5); 
       IsolatedStorageSettings.ApplicationSettings.Save(); 
      } 
      else 
      { 
       isolatedStorageSettingsCount.Add("count",5); 
       IsolatedStorageSettings.ApplicationSettings.Save(); 
      } 

以檢索下面的代碼您的計數值使用:

IsolatedStorageSettings isolatedStorageSettingsCount = IsolatedStorageSettings.ApplicationSettings; 
string strCount = (string)isolatedStorageSettingsCount["count"]; 
int count=Convert.ToInt32(strCount); 
+0

使用它你真的覺得有幫助 –

+0

當ISS中已經存在'count'時,你的代碼將會失敗。 – Romasz

+0

此代碼也有同樣的問題, 我應該怎麼做非常第一次計數? 我必須用零初始化它,但如果我這樣做,那麼它會每次都重新初始化它。 –

相關問題