I am creating a style for a button so that I can easily control what color it is when I hover or click it. When I first started creating this I was using normal triggers, but this didn’t work because I couldn’t have an animation for clicking it. I was told to use a VisualStateManager instead. That was in this question
This has worked amazingly so far, but now I’m trying to create a custom button where I can control what color it is when hovering your mouse over it or when you click it. I have been trying to do this using a TemplateBinding, but this didn’t work. So then I tried to use a RelativeSource where I set it to a TemplatedParent. This is a solution I found here. This for some reason didn’t work and I’m very much stuck here.
This is my button class:
public class Button : System.Windows.Controls.Button
{
public static readonly DependencyProperty HoverColorProperty = DependencyProperty.RegisterAttached(
nameof(HoverColor),
typeof(Color),
typeof(Button),
new PropertyMetadata());
public Color HoverColor
{
get => (Color)GetValue(HoverColorProperty);
set => SetValue(HoverColorProperty, value);
}
}
And here is my style
<Style TargetType="{x:Type controls:Button}">
<Setter Property="Foreground" Value="{DynamicResource TextBrush}" />
<Setter Property="BorderBrush" Value="{DynamicResource Surface1Brush}" />
<Setter Property="Background" Value="{DynamicResource BaseBrush}" />
<Setter Property="HoverColor" Value="{DynamicResource Surface1Color}" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type controls:Button}">
<Border x:Name="Border" CornerRadius="4"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualStateGroup.Transitions>
<VisualTransition From="MouseOver" To="Normal" GeneratedDuration="0:0:0.15" />
</VisualStateGroup.Transitions>
<VisualState x:Name="Normal" />
<VisualState x:Name="MouseOver">
<Storyboard>
<ColorAnimation Storyboard.TargetName="Border"
Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)"
To="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=HoverColor}" Duration="0:0:0.15" />
</Storyboard>
</VisualState>
<VisualState x:Name="Pressed">
<Storyboard>
<ColorAnimation Storyboard.TargetName="Border"
Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)"
To="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Background.(SolidColorBrush.Color)}" Duration="0:0:0.15" />
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>