Windows 操作系统提供了亮色主题(Light Mode)和暗色主题(Dark Mode),用户可以根据个人喜好和环境选择适合的主题模式。默认情况下 Avalonia 应用可以自适应主题的变更从而呈现出不同的颜色,这是因为设置了
RequestedThemeVariant
属性为
Default
。
<Application
xmlns
="https://github.com/avaloniaui"
xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml"
RequestedThemeVariant
="Default"
...
>
<!-- "Default" ThemeVariant follows system theme variant. "Dark" or "Light" are other available options. -->
<!-- "默认 "主题变量遵循系统主题变量。"深色 "或 "浅色 "是其他可用选项。-->
...
</Application
>
如果想自行定义一个可以随主题自动变换的颜色,就需要用到一项名为「主题变体」的技术。
在 Avalonia 中,主题变体特定的资源可以在 ResourceDictionary 中使用 ThemeDictionaries 属性进行定义。通常,开发人员使用 Light 或 Dark 作为主题变体的键。使用 Default 键标记后备资源字典,以防在其他主题字典中找不到主题变体或资源键。
以下是一个例子,我将资源字典直接放在了 Application 中。当然,放在其他地方也是可以的,比如 Window 类型。
<Application.Resources
>
<ResourceDictionary
>
<ResourceDictionary.ThemeDictionaries
>
<ResourceDictionary
x:Key
="Dark"
>
<SolidColorBrush
x:Key
='TestBackgroundBrush'
>
Red</SolidColorBrush
>
</ResourceDictionary
>
<ResourceDictionary
x:Key
="Light"
>
<SolidColorBrush
x:Key
='TestBackgroundBrush'
>
Green</SolidColorBrush
>
</ResourceDictionary
>
<ResourceDictionary
x:Key
="Default"
>
<SolidColorBrush
x:Key
='TestBackgroundBrush'
>
WhiteSmoke</SolidColorBrush
>
</ResourceDictionary
>
</ResourceDictionary.ThemeDictionaries
>
</ResourceDictionary
>
</Application.Resources
>
资源定义之后,就可以通过
DynamicResource
加资源键来访问:
<Border
Background
="{DynamicResource TestBackgroundBrush}"
>
<TextBlock
Text
="Hello World"
>
</TextBlock
>
</Border
>
如果切换 Windows 的颜色模式,就可以看到效果:
除此之外,强大的 Avalonia 还提供了一个名为
ThemeVariantScope
标签,用于控制特定范围内的主题变体。
<ThemeVariantScope
RequestedThemeVariant
="Dark"
>
<Border
Background
="{DynamicResource TestBackgroundBrush}"
>
<TextBlock
Text
="Hello World"
>
</TextBlock
>
</Border
>
</ThemeVariantScope
>
<ThemeVariantScope
RequestedThemeVariant
="Light"
>
<Border
Background
="{DynamicResource TestBackgroundBrush}"
>
<TextBlock
Text
="Hello World"
>
</TextBlock
>
</Border
>
</ThemeVariantScope
>
展示效果如下: