0

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>
Corentin Pane
  • 4,794
  • 1
  • 12
  • 29
Ednik
  • 27
  • 4
  • What are `Primary` and `Black`? These are nowhere defined. Also, how is the Button defined? – Lennart Jan 17 '23 at 08:33
  • @Lennart sorry, my mistake. I've added it to the question – Ednik Jan 17 '23 at 08:41
  • Your inner Button style is not applied because there is an explicit Style already applied to the button. Move the Style triggers up to the outer style and it'll work – Corentin Pane Jan 17 '23 at 08:45
  • Like this? If yes, it doesn't seem to work aswell. :( [Image](https://i.ibb.co/mqXyG6d/image.png) ` ` – Ednik Jan 17 '23 at 08:51

1 Answers1

0

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.

Corentin Pane
  • 4,794
  • 1
  • 12
  • 29