Why is my button style not applied when declared in the resources of another style?

48 Views Asked by At

I don't understand why this doesn't change the Background and Foreground while hovering the Button. It changes the CornerRadius of the Border tho.

ButtonStyle.xaml

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style TargetType="Button" x:Key="RoundedCorners">
        <Style.Resources>
            <Style TargetType="{x:Type Button}">
                <Style.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Background" Value="Red"/>
                        <Setter Property="Foreground" Value="Green"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
            <Style TargetType="Border">
                <Setter Property="CornerRadius" Value="5"/>
            </Style>
        </Style.Resources>
    </Style>
</ResourceDictionary>

LoginView.xaml

<Button Height="50"
        Width="200"
        Style="{StaticResource RoundedCorners}">
    LOGIN
</Button>
1

There are 1 best solutions below

0
On

In WPF, an explicit Style set locally through Style={StaticResource StyleKey} takes precedence over an implicit style matched through a TargetType, as detailed here.

Hence, only the outer Style is applied to your Button because it's given a key and epxlicitly set.

To fix it, you should meger the inner Style into the keyed Style like this:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style TargetType="Button" x:Key="RoundedCorners">
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Background" Value="Red"/>
                <Setter Property="Foreground" Value="Green"/>
            </Trigger>
        </Style.Triggers>
        <Style.Resources>
            <Style TargetType="Border">
                <Setter Property="CornerRadius" Value="5"/>
            </Style>
        </Style.Resources>
    </Style>
</ResourceDictionary>

This will properly change the Foreground when you hover it. The Background will still not change, but that's an entire different problem.