Search code examples
c#xamlsharedpreferencesmaui

Syntax for accessing Variables in public Settings Class


I found following thread:

After a lot of struggling to find the right answer, I was able to use [Preferences][1] to really easily get/set user settings without having to worry about saving and loading myself.

// getter
var value = Preferences.Get("nameOfSetting", "defaultValueForSetting");

// setter
Preferences.Set("nameOfSetting", value);

I wrapped mine in a property so it's easier to use:

public string FilePath
{
    get { return Preferences.Get(nameof(FilePath), ""); }
    set { Preferences.Set(nameof(FilePath), value); }
}

I tried a lot but cant manage to use the variables when wrapped in a property.

e.g. if I want to set the Labeltext to the Filepath setting from thread above:

Text = StandardSettings.get(Filepath);

or

Text = StandardSettings.Filepath{get};

The class StandardSettings is public and connected by "using" in my xaml. What would be the syntax for getting/setting the Filepath? Would be great to get the syntax for both xaml and c#.


Solution

  • I created a new project and everything worked correctly. Here is my code:

    public partial class NewPage1 : ContentPage
    {
          public string FileName
          {
                get { return Preferences.Default.Get(nameof(FileName),"NoName"); }
                set { Preferences.Default.Set(nameof(FileName), value); }
          }
    
          public NewPage1()
          {
                InitializeComponent();
        }
    
        private void Button_Clicked(object sender, EventArgs e)
        {
                this.FileName = "Hahaha";
                (sender as Button).Text = this.FileName;
        }
    }
    

    When I clicked the button, the button's text will change as Hahaha. And if I remove the this.FileName = "Hahaha";, it will be the default value NoName.

    Note: this.FileName = "Hahaha"; will call the FileName's set method. And (sender as Button).Text = this.FileName; will call its get method.