I am new to XAML, I want to change the background
of a button to the color of the BorderBrush
when I hover above it
Here's the code:
<Style TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="15">
<ContentPresenter HorizontalAlignment="Center"
VerticalAlignment="Center"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background"
Value="{Binding BorderBrush, RelativeSource={RelativeSource AncestorType={x:Type Button}}}"/>
<Setter Property="Cursor" Value="Hand"/>
</Trigger>
</Style.Triggers>
</Style>
The value of the Cursor changes as it should, the Background however doesn't.
I also tried RelativeSource={RelativeSource {x:Type BUtton}}
but it didn't work.
You have to use RelativeSource.Self
:
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background"
Value="{Binding BorderBrush, RelativeSource={RelativeSource Self}}"/>
<Setter Property="Cursor" Value="Hand"/>
</Trigger>
Be aware however that the Background Setter in the Style Trigger would be ignored if your directly assign the Button's Background like e.g.
<Button Background="Transparent" .../>
In that case move the Trigger to the ControlTemplate, with RelativeSource.TemplatedParent
:
<Style TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border x:Name="border"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="15">
<ContentPresenter HorizontalAlignment="Center"
VerticalAlignment="Center"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="border"
Property="Background"
Value="{Binding BorderBrush, RelativeSource={RelativeSource TemplatedParent}}"/>
<Setter TargetName="border"
Property="Cursor"
Value="Hand"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>