I’m stuck with Styles in WPF. I need the background gradient to change when the user hovers their mouse over the button, but I cannot figure out how to go about the change. This is the code I have so far:
<Style x:Key="Button_Green" TargetType="{x:Type Button}">
<Setter Property="FontSize" Value="11" />
<Setter Property="Foreground" Value="White"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border CornerRadius="2" BorderBrush="#387f38" BorderThickness="1">
<Border.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FF5BB75B" Offset="0" />
<GradientStop Color="#FF449B44" Offset="1" />
</LinearGradientBrush>
</Border.Background>
<ContentPresenter x:Name="ButtonContentPresenter" VerticalAlignment="Center" HorizontalAlignment="Center"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background">
<Setter.Value>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FF5BB75B" Offset="0" />
<GradientStop Color="#FF398239" Offset="1" />
</LinearGradientBrush>
</Setter.Value>
</Setter>
<Setter Property="Cursor" Value="Hand" />
</Trigger>
</Style.Triggers>
</Style>
The mouse cursor changes properly, but the background gradient does not change.
You need to set the target of your setter to the
Borderelement that you defined in yourControlTemplate. Currently, it is targeting theBackgroundproperty of theButtonitself, which is hidden by your customControlTemplate.Here, I added a
x:Nameproperty to theBorderelement so that it can be referenced with theTargetNameproperty on theSetter.