Search code examples
xamarinxamarin.formsxamarin.android

Save the state of switch using essential.prefences in xamarin.forms


I want to save the state of a switch in Xamarin.forms even when the user close the application, I followed the Microsoft tutorial about the Xamarin essentials preferences API tutorialXamarin.Essentials: Preferences. Below is the switch code in Xaml and Xaml.cs

<StackLayout Orientation="Horizontal" IsVisible="True" Margin="50,10">
    <Label Text="Remember Me:" />
    <Switch IsToggled="{Binding SwitchMe}" />
</StackLayout>
public bool SwitchMe
{
    get => Preferences.Get(nameof(SwitchMe), false);
    set
    {
        Preferences.Set(nameof(SwitchMe), value =true);
        OnPropertyChanged(nameof(SwitchMe));
    }
}

Problem: The switch state will return to its defaults when the application is closed.

Is there a problem in my code ? I have added all the requirements in the android and ios for xamarin.essentials.


Solution

  • Thank you guys, the solution was like the following:

     public bool SwitchMe
        {
            get => Preferences.Get(nameof(SwitchMe), false);
            set
            {
    
                Preferences.Set(nameof(SwitchMe), value);
                PropertyChanged(this, new PropertyChangedEventArgs(nameof(SwitchMe)));
            }