Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Trigger Not Working As Intended

I want a red button that turns black when the mouse hovers over it.

    <Button Content="Hover me" Grid.Column="3" Grid.Row="3">
        <Button.Style>
            <Style TargetType="{x:Type Button}">
                <Setter Property="Background" Value="Red"/>
                <Style.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Background" Value="Black"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Button.Style>
    </Button>

However, my problem is that when I hover over the button, it turns into the default Windows style with a gradient gray appearance.

like image 633
Clement Hoang Avatar asked Jul 20 '13 05:07

Clement Hoang


1 Answers

Try it

<Window.Resources>
    <Style x:Key="MyButtonStyle" TargetType="{x:Type Button}">
        <Setter Property="Background" Value="Red"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Border Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}">
                        <ContentPresenter x:Name="PART_Content"
                                          VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                                          HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                          TextElement.Foreground="{TemplateBinding Foreground}"></ContentPresenter>                        </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Background" Value="Black"/>
                <Setter Property="Foreground" Value="White"/>
            </Trigger>
        </Style.Triggers>
    </Style>
</Window.Resources>

and apply the custom Style as following

<Button Content="Hover me" Style="{StaticResource MyButtonStyle}" Height="30" Width="100"/>

The reason is the default Aero style of a Button. It has a chrome defined in ControlTemplate, which has it own behavior on various mouse events. So That over write your trigger call.

So you must override default ControlTemplate of Button to achieve your desired result.

like image 90
Nitesh Avatar answered Oct 02 '22 14:10

Nitesh