当系统主题改变时,如何从应用程序中获取事件?

How to get an event from the application when the system theme changes?

由于 Uno 尚不支持 iOS 资产的主题限定符,我必须在我的项目中求助于辅助服务,以提供为暗模式创建的图像的替代路径。但是,这会导致资产 URL 被评估一次,而不是在应用 运行 时更改系统主题时。当系统主题改变时,有没有办法从应用程序中获取正在调用的事件或方法?

如果您希望某些 UI 资源根据主题进行更改,您可以使用 ThemeResource with ThemeDictionaries

Uno 项目中的示例

主题词典中主题资源的声明

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="using:Uno.Gallery.Views.Styles.Application">
    <ResourceDictionary.ThemeDictionaries>
        <!-- Light Theme -->
        <ResourceDictionary x:Key="Light">
            <x:String x:Key="UnoLogoImageSource">ms-appx:///Assets/UnoGalleryLogo_Light.png</x:String>
        </ResourceDictionary>

        <!-- Dark Theme -->
        <ResourceDictionary x:Key="Dark">
            <x:String x:Key="UnoLogoImageSource">ms-appx:///Assets/UnoGalleryLogo_Dark.png</x:String>
        </ResourceDictionary>
    </ResourceDictionary.ThemeDictionaries>
</ResourceDictionary>

参考代码: https://github.com/unoplatform/Uno.Gallery/blob/master/Uno.Gallery/Uno.Gallery.UWP/Views/Colors.xaml#L11

页面中的用法

<Image Source="{ThemeResource UnoLogoImageSource}" />

参考代码:https://github.com/unoplatform/Uno.Gallery/blob/45e490668890c3a9db1e28a5b3de2a61822b07ca/Uno.Gallery/Uno.Gallery.UWP/Views/Shell.xaml#L45

为了完整起见,您还可以使用 UISettings.ColorValuesChanged 事件来观察主题变化。此外,Microsoft Community Toolkit 围绕它提供了一个非常好的包装器 - ThemeListener,它也可以在 Uno Platform 应用程序中使用。

理想情况下,我们还希望支持用于资产消歧的主题限定符 - 类似于 -scale-150 等。它允许您使用后缀让系统选择浅色或深色资产。您可以投票 this GitHub issue 来帮助我们确定优先顺序。