David
David

Reputation: 537

WPF – Keep Trigger If Corresponding Property Is Set

Is it possible to keep the Trigger within Style if the corresponding property is set outside the Style?

The second Button works fine, but the Trigger does not work on the first one Button.

<StackPanel>
    <StackPanel.Resources>
        <Style TargetType="{x:Type Button}">
            <Style.Triggers>
                <Trigger Property="IsMouseOver"
                         Value="True">
                    <Setter Property="Foreground"
                            Value="GreenYellow" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </StackPanel.Resources>
    <Button Foreground="Orange">The First Button</Button>
    <Button>The Second Button</Button>
</StackPanel>

Upvotes: 0

Views: 37

Answers (2)

Dominic Jonas
Dominic Jonas

Reputation: 5005

You have to declare your default value in the Style.

<StackPanel>
    <StackPanel.Resources>
        <Style TargetType="{x:Type Button}">
            <Setter Property="Foreground" Value="Orange"/>
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Foreground" Value="GreenYellow" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </StackPanel.Resources>
    <Button>The First Button</Button>
    <Button>The Second Button</Button>
</StackPanel>

Have a look at the Dependency Property Setting Precedence List on https://msdn.microsoft.com/en-us/library/ms743230.aspx

If you want to make it dynamic. You have to write your own CustomButton with a additional DependencyProperty and write your own Style for it.

Upvotes: 1

mm8
mm8

Reputation: 169200

The reason why this doesn't work is that local dependency property values takes precedence over property values set by setters: https://msdn.microsoft.com/en-us/library/ms743230(v=vs.110).aspx.

So no, it is not possible to use a Setter in a Style to set a property that has been set to a local value:

<Button Foreground="Orange">The First Button</Button>

Upvotes: 1

Related Questions