Adding on Microsoft_DN answer, if anyone wants to reuse the style for different buttons with different color we can create a custom Button class with hovercolor
and bgcolor
DependencyProperty.
HoverButton.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace StackOverflow
{
public class HoverButton : Button
{
public static readonly DependencyProperty hoverColorProperty = DependencyProperty.Register
(
"hoverColor",
typeof(SolidColorBrush),
typeof(HoverButton),
new PropertyMetadata(new BrushConverter().ConvertFrom("#5D5D5D"))
);
public SolidColorBrush hoverColor
{
get { return (SolidColorBrush)GetValue(hoverColorProperty); }
set { SetValue(hoverColorProperty, value); }
}
public static readonly DependencyProperty bgColorProperty = DependencyProperty.Register
(
"bgColor",
typeof(SolidColorBrush),
typeof(HoverButton),
new PropertyMetadata(new SolidColorBrush(Colors.Red))
);
public SolidColorBrush bgColor
{
get { return (SolidColorBrush)GetValue(bgColorProperty); }
set { SetValue(bgColorProperty, value); }
}
}
}
Then add the following style in App.xaml file inside Application.Resources tag
<Style TargetType="{x:Type StackOverflow:HoverButton}" x:Key="customButton">
<Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Path = bgColor}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border Background="{TemplateBinding Background}">
<ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Center" Margin="{TemplateBinding Padding}"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value ="{Binding RelativeSource={RelativeSource Self}, Path = hoverColor}" />
</Trigger>
</Style.Triggers>
</Style>
The we can use the style as in HoverButton
<myApp:HoverButton Height="20" Width="20" Style="{StaticResource customButton}" bgColor="Orange" hoverColor="Blue">
</myApp:HoverButton>
Because HoverButton is not using the project namespace we need to add
xmlns:myApp = "clr-namespace:StackOverflow"
in both Application tag in app.xaml and Window tag in MainWindow.xaml file.
Sample: https://github.com/ayush1920/Stackoverflow/tree/main/WPF%20HoverButton