基于系统主题切换AvaloniaUI自定义控件样式的问题
Avalonia 11.0.5 自定义控件跟随系统深浅主题切换的正确实现
你之前的写法问题在于直接同时加载了浅色和深色主题样式,后加载的深色样式会覆盖浅色的,而且没有关联系统主题的切换逻辑。下面是两种可行的解决方式:
方法一:在单个样式文件中使用主题变体选择器
不需要拆分两个主题文件,直接在样式里针对不同主题变体写规则:
修改App.xaml,启用系统主题跟随
<Application xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="YourNamespace.App" RequestedThemeVariant="Default"> <!-- 设置为Default跟随系统主题 --> <Application.Styles> <StyleInclude Source="CustomStyles.axaml" /> </Application.Styles> </Application>
CustomStyles.axaml 样式文件
<Styles xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <!-- 浅色主题下Button样式 --> <Style Selector="Button:is-light"> <Setter Property="Background" Value="LightGray" /> </Style> <!-- 深色主题下Button样式 --> <Style Selector="Button:is-dark"> <Setter Property="Background" Value="DarkGray" /> </Style> </Styles>
方法二:拆分主题文件并结合主题变体加载
如果坚持要分开浅色和深色主题文件,可以通过Style的IsEnabled绑定到当前主题变体来控制加载:
App.xaml 修改
<Application xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" x:Class="YourNamespace.App" RequestedThemeVariant="Default"> <Application.Styles> <StyleInclude Source="LightTheme.axaml" IsEnabled="{Binding $self.RequestedThemeVariant, Converter={x:Static d:ThemeVariantConverter.Instance}, ConverterParameter=Light}" /> <StyleInclude Source="DarkTheme.axaml" IsEnabled="{Binding $self.RequestedThemeVariant, Converter={x:Static d:ThemeVariantConverter.Instance}, ConverterParameter=Dark}" /> </Application.Styles> </Application>
LightTheme.axaml 保持不变
<Styles xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Style Selector="Button"> <Setter Property="Background" Value="LightGray" /> </Style> </Styles>
DarkTheme.axaml 保持不变
<Styles xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Style Selector="Button"> <Setter Property="Background" Value="DarkGray" /> </Style> </Styles>
另外注意你写的<Button Content="Click me" Classes="Button" />里Classes="Button"是多余的,Button本身就属于Button选择器,直接写<Button Content="Click me" />即可。
内容的提问来源于stack exchange,提问作者Sfairait
相关产品推荐
相关产品推荐

