使用xamarin.forms中的essential.preferences保存开关的状态



我想在Xamarin.forms中保存开关的状态,即使用户关闭应用程序,我也按照Microsoft教程中关于Xamarin必需品首选项API教程Xamarin.essentials:首选项。以下是Xaml和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));
}
}

问题:当应用程序关闭时,开关状态将返回到默认状态。

我的代码有问题吗?我已经添加了xamarin.essentials.的android和ios中的所有要求

直接从ViewModel:中的属性引用Xamarin.Essentials.Preferences

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

谢谢大家,解决方案如下:

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

最新更新