Xamarin, how to convert my Xamarin.plugins.setting

2019-08-16 17:25发布

问题:

Ive been using Montemagno's plugin for saving Settings but someone mentioned it's better to user preferences.essential. There's not much tutorial on it.

I'm having problem the getting and setting the value and accessing it from another file from where I set it.

//Settings.cs
public static string NameSettings
{
    get
    {
        return AppSettings.GetValueOrDefault(SettingsnameKey, SettingsDefault);
    }
    set
    {
        AppSettings.AddOrUpdateValue(SettingsnameKey, value);
    }
}

public static string DrainquantitySettings
{
    get
    {
        return AppSettings.GetValueOrDefault(SettingsdrainxKey, SettingsDefault);
    }
    set
    {
        AppSettings.AddOrUpdateValue(SettingsdrainxKey, value);
    }
}

//this is how i get it in another file
drainxPicker.SelectedItem = Settings.DrainquantitySettings;

nameEntry.Text = Settings.NameSettings;

//to set it
Settings.NameSettings = username;
Settings.DrainquantitySettings = item;


//to convert to preferences?
public static NameSettings
{
    get => Preferences.Get(nameof(NameSettings), username);
    set => Preferences.Set(nameof(NameSettings), value);
}

//to use it??
nameEntry.Text = Preferences.Settings.NameSettings;

//to set it??
Preferences.Settings.NameSettings = username;

回答1:

I just did this very thing

public static bool UploadOnlyOverWifi
{
    get => Preferences.Get(nameof(UploadOnlyOverWifi), false);
    set => Preferences.Set(nameof(UploadOnlyOverWifi), value);
}


回答2:

According to Jason's reply, you can use Preferences.Set() to save value ,and using Preferences.Get() to retrieve value from preference.

 <StackLayout>
        <Entry x:Name="entry1" />
        <Button
            x:Name="btnsave"
            Clicked="Btnsave_Clicked"
            Text="Save" />
        <Button
            x:Name="btnget"
            Clicked="Btnget_Clicked"
            Text="Get" />
    </StackLayout>

private void Btnsave_Clicked(object sender, EventArgs e)
    {
        Preferences.Set("key1", entry1.Text);
    }

    private void Btnget_Clicked(object sender, EventArgs e)
    {
        string value1 = Preferences.Get("key1","");
        DisplayAlert("Success", "Your Value is " + value1, "OK");
    }