【问题标题】:Save the state of switch using essential.prefences in xamarin.forms使用 xamarin.forms 中的 essential.preferences 保存 switch 的状态
【发布时间】:2021-05-19 18:18:23
【问题描述】:

即使用户关闭应用程序,我也想在 Xamarin.forms 中保存开关的状态,我按照关于 Xamarin 基本首选项 API 教程Xamarin.Essentials: Preferences 的 Microsoft 教程进行操作。下面是 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));
    }
}

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

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

【问题讨论】:

  • 你为什么写value = true
  • 只是为了检查它是否会在关闭应用后改变状态
  • 您是否在恢复应用时检查过偏好设置是否正确?
  • @Jason 如何检查?抱歉,我是 Xamarin 世界的新手
  • 像处理任何 C# 项目一样使用调试器

标签: xamarin xamarin.forms xamarin.android


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    谢谢各位,解决方法如下:

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

    【讨论】:

    • 不要忘记接受你的回答,这将帮助更多有类似问题的人:)
    猜你喜欢
    • 1970-01-01
    • 2018-09-24
    • 1970-01-01
    • 1970-01-01
    • 2010-09-14
    • 1970-01-01
    • 1970-01-01
    • 2019-11-10
    • 1970-01-01
    相关资源
    最近更新 更多