2016-05-17 101 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

太棒了。我也在研究领域。尽管感谢您的反馈。 –

相关问题