WPF 从按钮样式覆盖触发器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44905233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 14:07:16  来源:igfitidea点击:

WPF Override a trigger from a button style

c#wpfxamlwpf-style

提问by Ralph

I have below button style in window resources:

我在窗口资源中有以下按钮样式:

<Style x:Key="MyStyle" TargetType="{x:Type Button}">

    <Setter Property="BorderBrush" Value="Transparent"/>
    <Setter Property="BorderThickness" Value="0 0 0 3"/>

    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="BorderBrush" Value="Orange" />
        </Trigger>
        <Trigger Property="IsPressed" Value="True">
            <Setter Property="BorderBrush" Value="Red" />
        </Trigger>         
    </Style.Triggers>

</Style>

This style is shared by two wpf buttons. But there is a button I want to show a custom color when it is pressed, the color will be green.

此样式由两个 wpf 按钮共享。但是有一个按钮我想在按下时显示自定义颜色,颜色将为绿色。

So in this special button I would like to override the value specified for borderbrush property in the trigger, instead of Red I would like Green.

所以在这个特殊的按钮中,我想覆盖触发器中为 borderbrush 属性指定的值,而不是红色,我想要绿色。

How to do this?

这该怎么做?

回答by mm8

You could set the BorderBrushproperty using a {DynamicResource}that you can override:

您可以BorderBrush使用{DynamicResource}可以覆盖的属性设置属性:

<SolidColorBrush x:Key="pressed" Color="Red" />
<Style x:Key="MyStyle" TargetType="{x:Type Button}">
    <Setter Property="BorderBrush" Value="Transparent"/>
    <Setter Property="BorderThickness" Value="0 0 0 3"/>
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="BorderBrush" Value="Orange" />
        </Trigger>
        <Trigger Property="IsPressed" Value="True">
            <Setter Property="BorderBrush" Value="{DynamicResource pressed}" />
        </Trigger>
    </Style.Triggers>
</Style>
...
<Button Content="Red" Style="{StaticResource MyStyle}" />

<Button Content="Green" Style="{StaticResource MyStyle}">
    <Button.Resources>
        <SolidColorBrush x:Key="pressed" Color="Green" />
    </Button.Resources>
</Button>

Or you could create another Stylethat overrides the entire trigger:

或者您可以创建另一个Style覆盖整个触发器:

<Button Content="Green">
    <Button.Style>
        <Style TargetType="Button" BasedOn="{StaticResource MyStyle}">
            <Style.Triggers>
                <Trigger Property="IsPressed" Value="True">
                    <Setter Property="Foreground" Value="Green" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>