添加 Microsoft_DN 答案,如果有人想为不同颜色的不同按钮重用样式,我们可以使用 hovercolor 和 bgcolor DependencyProperty 创建自定义 Button 类。
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); }
}
}
}
然后在App.xaml文件中Application.Resources标签内添加如下样式
<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>
我们可以使用 HoverButton 中的样式
<myApp:HoverButton Height="20" Width="20" Style="{StaticResource customButton}" bgColor="Orange" hoverColor="Blue">
</myApp:HoverButton>
因为 HoverButton 没有使用我们需要添加的项目命名空间
xmlns:myApp = "clr-namespace:StackOverflow"
在 app.xaml 中的 Application 标记和 MainWindow.xaml 文件中的 Window 标记中。
示例:https://github.com/ayush1920/Stackoverflow/tree/main/WPF%20HoverButton