Search code examples
wpf

WPF trigger doesn't work


I want to change my Button Background, Margin, and Foreground when the mouse hovers, But It changes only the foreground. Please help..

<Window x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:coupleofbuttons"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button x:Name="ButtonX" Margin="10,10,0,0" Content="Button" HorizontalAlignment="Left"  VerticalAlignment="Top" Width="100" Height="46" Background="Green"  BorderThickness="0,0,0,7">
            <Button.Style>
                <Style TargetType="{x:Type Button}">
                    <Style.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Background" Value="DarkGoldenrod"/>
                            <Setter Property="Foreground" Value="Green"/>
                            <Setter Property="Margin" Value="10,20,0,0"/>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </Button.Style>
        </Button>
    </Grid>
</Window>

Solution

  • If a property is set in an attribute, as you've done with Margin and Background, that overrides anything the Style does, so a Style trigger can't change it.

    Set the default values for those properties in Setters in the Style, but not in the Style.Triggers section. And take off the Margin and Background properties you have on it now.