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
>
展示效果如下: