WPF Override a trigger from a button style

Ralph picture Ralph · Jul 4, 2017 · Viewed 10.8k times · Source

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.

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.

How to do this?

Answer

mm8 picture mm8 · Jul 4, 2017

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

<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 Style that overrides the entire trigger:

<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>