在Microsoft_DN的回答上补充一点,如果有人想要重复使用不同颜色的样式来创建不同的按钮,我们可以创建一个自定义按钮类,其中包含
hovercolor
和
bgcolor
依赖属性。
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:Key="customButton">
<Setter Property="Background" Value=", Path = bgColor}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="">
<Border Background="">
<ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Center" Margin=""/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value =", Path = hoverColor}" />
</Trigger>
</Style.Triggers>
</Style>
我们可以使用鼠标悬停按钮中的样式。
<myApp:HoverButton Height="20" Width="20" Style="{StaticResource customButton}" bgColor="Orange" hoverColor="Blue">
</myApp:HoverButton>
由于HoverButton没有使用项目命名空间,我们需要在
app.xaml文件中的Application标记和
MainWindow.xaml文件中的Window标记中分别添加
xmlns:myApp = "clr-namespace:StackOverflow"
示例:
https://github.com/ayush1920/Stackoverflow/tree/main/WPF%20HoverButton