Xamarin表单共享偏好交叉

use*_*593 12 cross-platform application-settings sharedpreferences xamarin.forms

我想知道以跨平台方式操作应用程序设置的最佳解决方案是什么.

在iOS中,我们可以在设置屏幕中更改应用程序外部的设置,但我们在Windows手机和Android中没有.

因此,我的想法是在应用程序内部创建一个正常的页面/屏幕,显示我的所有应用程序设置,并具有Save()和Get()方法的接口,我可以使用DependencyServices为每个设备实现特定的方法.

这是正确的方法吗?

Dan*_*rda 20

  1. Application子类具有静态Properties字典,可用于存储数据.可以使用Application.Current.Properties从Xamarin.Forms代码中的任何位置访问它.
Application.Current.Properties ["id"] = someClass.ID;

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

属性字典将自动保存到设备中.当应用程序从后台返回或甚至重新启动后,添加到字典中的数据将可用.Xamarin.Forms 1.4在Application类上引入了一个额外的方法SavePropertiesAsync()- 可以调用它来主动持久化Properties字典.这是为了允许您在重要更新后保存属性,而不是冒着因崩溃或被操作系统杀死而无法将其序列化的风险.

https://developer.xamarin.com/guides/cross-platform/xamarin-forms/working-with/app-lifecycle/

  1. Xamarin.Forms插件,它使用本机设置管理.

    • Android:SharedPreferences
    • iOS:NSUserDefaults
    • Windows Phone:IsolatedStorageSettings
    • Windows应用商店/ Windows Phone RT:ApplicationDataContainer

https://github.com/jamesmontemagno/Xamarin.Plugins/tree/master/Settings