Search code examples
wpfxaml

WPF Control Style of Button not detecting IsMouseOver


So I am trying to create button style (background opacity to black with 20% alpha and default colour of text changes to clear white) with using ResourceDictionary. I do include file into App.xaml like:

        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Style/ButtonStyles.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>

and to button I am applying x:Key, Style="{StaticResource TopBarButtons}"

So my style of it looks like (random colours just to test):

    <Style x:Key="TopBarButtons" TargetType="{x:Type Button}">
        <Setter Property="Background" Value="HotPink"></Setter>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Border CornerRadius="5" Background="{TemplateBinding Background}" BorderThickness="1" Padding="5">
                        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Foreground" Value="Red" />
                <Setter Property="Background" Value="Lime" />
            </Trigger>
        </Style.Triggers>
    </Style>

But none of those are detecting, nothing change at all.. What's my error?


Solution

  • Setting

    <Button ... Background="Transparent"/>
    

    directly on the Button sets a so-called local value, which takes higher precedence than a value set by a Style Setter or a Setter in a Style Trigger.

    Any value that should be changed by a Style Trigger can only be initialized by a Style Setter, e.g.

    <Setter Property="Background" Value="Transparent"/>
    

    For reference, see Dependency property value precedence.