从样式触发器覆盖样式

从样式触发器覆盖样式

本文介绍了WPF 从样式触发器覆盖样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Radiobutton,它的样式设置为使其显示为 ToggleButton,并且我想将其默认背景颜色设置为绿色,但是当它处于活动状态/选中时,我希望它改变颜色.在下面的示例中,我希望它是蓝色的.无论我尝试什么,绿色都不会被覆盖.我错过了什么?

I have a Radiobutton, which has styling set to make it appear as a ToggleButton, and I want to set its default background color to green, but when it is active/checked i want it to change color. In my example below I'd like it to be blue. No matter what I try the green color never gets overridden. What am I missing?

按钮:

<RadioButton GroupName="Rating" Background="Green" Style="{StaticResource RatingToggleButtons}" x:Name="Normal" Content="Normal" Grid.Row="0" />

风格:

        <Style x:Key="RatingToggleButtons" TargetType="{x:Type ToggleButton}" BasedOn="{StaticResource MahApps.Metro.Styles.MetroToggleButton}">
        <Setter Property="Margin" Value="5 5 5 5" />
        <Setter Property="MinWidth" Value="100"/>
        <Setter Property="MinHeight" Value="50"/>
        <Style.Triggers>
            <Trigger Property="IsChecked" Value="True">
                <Setter Property="Background" Value="Blue"/>
                <Setter Property="Foreground" Value="White"/>
            </Trigger>
        </Style.Triggers>
    </Style>

推荐答案

本地值优先于样式设置的值这一事实:https://docs.microsoft.com/en-us/dotnet/framework/wpf/advanced/dependency-property-value-precedence

The fact that local values take precedence over values set by styles: https://docs.microsoft.com/en-us/dotnet/framework/wpf/advanced/dependency-property-value-precedence

所以不要像这样设置本地值:

So instead of setting a local value like this:

<RadioButton ... Background="Green" ... />

...你应该在 Style 中定义默认值:

...you should define the default value in the Style:

<Style TargetType="{x:Type ToggleButton}">
    <Setter Property="Background" Value="Green"/>
    <Setter Property="Margin" Value="5 5 5 5" />
    <Setter Property="MinWidth" Value="100"/>
    <Setter Property="MinHeight" Value="50"/>
    <Style.Triggers>
        <Trigger Property="IsChecked" Value="True">
            <Setter Property="Background" Value="Blue"/>
            <Setter Property="Foreground" Value="White"/>
        </Trigger>
    </Style.Triggers>
</Style>

...再次避免设置 RadioButton 元素的 Background 属性:

...and again avoid setting the Background property of the RadioButton element:

<RadioButton GroupName="Rating" Style="{StaticResource RatingToggleButtons}" x:Name="Normal" Content="Normal" Grid.Row="0" />

这篇关于WPF 从样式触发器覆盖样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 08:49