You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Avalonia UI桌面应用中如何设置选中ToggleButton的背景色

解决Avalonia UI中ToggleButton选中状态背景色不生效的问题

你的代码里Padding生效但Background不生效,核心原因是Avalonia的ToggleButton默认模板中,选中状态的背景由模板内部的子元素(比如名为BackgroundElement的Border)控制,而非直接使用ToggleButton自身的Background属性。直接设置ToggleButton的Background会被模板内的默认样式覆盖。

解决方案1:修改模板内部元素样式(推荐)

通过样式选择器深入到ToggleButton的模板内部,直接修改负责背景的Border元素样式:

<UserControl.Styles>
    <!-- 覆盖选中状态下模板内背景Border的颜色 -->
    <Style Selector="ToggleButton:checked /template/ Border#BackgroundElement">
        <Setter Property="Background" Value="Red"/>
    </Style>
    <!-- 保留内边距设置 -->
    <Style Selector="ToggleButton:checked">
        <Setter Property="Padding" Value="40"/>
    </Style>
</UserControl.Styles>

这里/template/是Avalonia样式语法中定位控件模板内部元素的关键字,Border#BackgroundElement对应默认模板里负责背景的Border(其x:Name为BackgroundElement)。

解决方案2:重写ToggleButton的ControlTemplate

如果需要完全自定义ToggleButton外观,可以重写整个模板,在触发器中直接设置选中状态的背景:

<UserControl.Styles>
    <Style Selector="ToggleButton">
        <Setter Property="Template">
            <ControlTemplate>
                <Border x:Name="BackgroundElement"
                        Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}"
                        Padding="{TemplateBinding Padding}">
                    <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                      VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                </Border>
                <ControlTemplate.Triggers>
                    <!-- 选中状态时设置背景色 -->
                    <Trigger Property="IsChecked" Value="True">
                        <Setter TargetName="BackgroundElement" Property="Background" Value="Red"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter>
        <Setter Property="Padding" Value="40" />
    </Style>
</UserControl.Styles>

内容的提问来源于stack exchange,提问作者Ben Harden

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 04:55:02