2016-05-17 42 views
17

如何在Xamarin.Forms中將應用程序設置存儲和檢索爲鍵值對? 與應用程序關閉時一樣,我們可以存儲用戶首選項,重新啓動應用程序時,我們可以獲取這些值。如何在Xamarin.Forms中存儲應用程序設置

+0

https://forums.xamarin.com/discussion/41680/application-current-properties-can-not-persist-in -android-using-xf-1-42 –

回答

30

這是可以做到這樣也使用Properties Dictionary

用於存儲數據:

Application.Current.Properties ["id"] = someClass.ID; 

用於取入數據:

if (Application.Current.Properties.ContainsKey("id")) 
{ 
    var id = Application.Current.Properties ["id"] as int; 
    // do something with id 
} 

REF:https://developer.xamarin.com/guides/xamarin-forms/working-with/application-class/#Properties_Dictionary

+0

請注意,您不應將其用於用戶設置。這些屬性被序列化爲一個xml文件,並且不使用底層平臺的本機設置/首選項機制。例如。在iOS中,它不會將項目存儲在NSUserDefaults中。您將無法從系統的設置包(https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/UserDefaults/Preferences/Preferences.html) – LanderV

+0

Application.Current修改它。屬性更多地關於跨激活保留應用程序狀態(OnStart/OnSleep/OnResume) – LanderV

0

Application對象(在VS中,你得到一個繼承自它的類App,我認爲Xamarin Studio模板可能略有不同)有一個Properties字典專門用於此目的。如果您需要確保您的資產馬上得到保存,您可以撥打Application.SavePropertiesAsync方法。

4

我用Settings Plugin for Xamarin And WindowsXamarin.Forms,因爲這上攻在器件級實現,你可以從任何形式的項目訪問這些設置,PCL庫或應用程式內您的本地項目。

  • 的NuGet:Xam.Plugins.Settings

private const string UserNameKey = "username_key"; 
private static readonly string UserNameDefault = string.Empty; 

public static string UserName 
{ 
    get { return AppSettings.GetValueOrDefault<string>(UserNameKey, UserNameDefault); } 
    set { AppSettings.AddOrUpdateValue<string>(UserNameKey, value); } 
} 
+0

akavache,你用過那個嗎?@SushiHangover –

+0

@AkashAmin幾乎我所有的應用程序裏面都有'Akavache'(使用它進行緩存但是想要移動到Realm的速度併爲未來的項目刪除SQLite的依賴)。但是,對於存儲一些應用程序設置,它是種殺死... – SushiHangover

+0

太棒了。我也在研究領域。儘管感謝您的反饋。 –

相關問題