0

目前我只在 Android 模拟器上进行测试。我已经安装了 Theme Nuget 包。

在我的 App 构造函数中,我有:

        // Load the desired theme (default to Light)
        if (Current.Properties.TryGetValue("Theme", out object theme))
            Resources = theme as ResourceDictionary;
        else
            Resources = new LightThemeResources();

然后我在 App 类中有一个方法:

    public async Task SwitchTheme()
    {
        // Switch the current theme from List to Dark to Light
        if (Resources?.GetType() == typeof(DarkThemeResources))
            Resources = new LightThemeResources();
        else
            Resources = new DarkThemeResources();

        // Persist the Theme
        Current.Properties.Add("Theme", Resources);
        await Current.SavePropertiesAsync();
    }

当我调用该方法时,主题会从明暗等切换。但是当我重新启动应用程序时,它始终默认为 Light。好像“等待 Current.SavePropertiesAsync();” 不工作。

谁能提出问题可能是什么?

4

1 回答 1

2

Xamarin FormsProperties旨在与可轻松序列化的 C# 值类型和对象一起使用,而不是与Resources.

文档

保存在属性字典中的值必须是原始类型,例如整数或字符串。尝试保存引用类型,特别是集合,可能会静默失败。

All you really need to do is store a string value - either 'light' or 'dark' and then load the appropriate theme based on that. You don't actually need to store the theme itself.

于 2019-07-29T00:35:28.423 回答