Xamarin Forms Sharedpreferences cross

旧街凉风 提交于 2019-12-01 02:58:35
  1. The Application subclass has a static Properties dictionary which can be used to store data. This can be accessed from anywhere in your Xamarin.Forms code using Application.Current.Properties.
Application.Current.Properties ["id"] = someClass.ID;

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

The Properties dictionary is saved to the device automatically. Data added to the dictionary will be available when the application returns from the background or even after it is restarted. Xamarin.Forms 1.4 introduced an additional method on the Application class - SavePropertiesAsync() - which can be called to proactively persist the Properties dictionary. This is to allow you to save properties after important updates rather than risk them not getting serialized out due to a crash or being killed by the OS.

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

  1. Xamarin.Forms plugin which uses the native settings management.

    • Android: SharedPreferences
    • iOS: NSUserDefaults
    • Windows Phone: IsolatedStorageSettings
    • Windows Store / Windows Phone RT: ApplicationDataContainer

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

I tried using the Application.Current.Properties Dictionary and had implementation problems.

A solution that worked with very little effort was James Montemagno's Xam.Plugin.Settings NuGet. GitHub Installing the NuGet automagically creates a Helpers folder with Settings.cs. To create a persisted setting you do:

    private const string QuestionTableSizeKey = "QuestionTableSizeKey";
    private static readonly long QuestionTableSizeDefault = 0;

and

    public static long QuestionTableSize
    {
        get
        {
            return AppSettings.GetValueOrDefault<long>(QuestionTableSizeKey, QuestionTableSizeDefault);
        }
        set
        {
            AppSettings.AddOrUpdateValue<long>(QuestionTableSizeKey, value);
        }
    }

Access and setting in the app then looks like:

namespace XXX
{
    class XXX
    {
        public XXX()
        {
                long myLong = 495;
                ...
                Helpers.Settings.QuestionTableSize = myLong;
                ...
                long oldsz = Helpers.Settings.QuestionTableSize;                   
        }
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!