How to store App settings in Xamarin.Forms

后端 未结 4 2071
攒了一身酷
攒了一身酷 2020-12-05 09:59

How can we store and retrieve App settings as key,value pair in Xamarin.Forms? Like when the app is closed we can store the user preferences and on restarting of the App we

相关标签:
4条回答
  • 2020-12-05 10:06

    The Application object (in VS you get an App class that inherits from it, I think the Xamarin Studio template might be slightly different) has a Properties dictionary that is specifically for this. If you need to make sure your properties get saved right away, there is a Application.SavePropertiesAsync method you can call.

    0 讨论(0)
  • 2020-12-05 10:10

    I use Settings Plugin for Xamarin And Windows for Xamarin.Forms, the upside since this is implemented at the device-level, you can access these settings from any Forms project, PCL library OR your native project within your app.

    • 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 讨论(0)
  • 2020-12-05 10:21

    It can be done this way too using Properties Dictionary

    for storing data:

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

    for fetching data:

    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 讨论(0)
  • 2020-12-05 10:24

    You can use the preferences included with Xamarin.Essential.

            /* You need to using Xamarin.Essentials
            If you do not have Xamarin.Essentials installed,
            install it from (NuGet Package Manager)
            */
    
            // Add a reference to Xamarin.Essentials in your class
            using Xamarin.Essentials;
    
            // To save a value for a given key in preferences
            Preferences.Set("my_key", "my_value");
    
            // To retrieve a value from preferences or a default if not set
            var myValue = Preferences.Get("my_key", "default_value");
    
            // To check if a given key exists in preferences
            bool hasKey = Preferences.ContainsKey("my_key");
    
            // To remove the key from preferences
            Preferences.Remove("my_key");
    
            // To remove all preferences
            Preferences.Clear();
    

    Have a look at this link: https://docs.microsoft.com/en-us/xamarin/essentials/preferences?tabs=android

    0 讨论(0)
提交回复
热议问题