我们制作一个鼠标经过改变背景色的Button。
点解解决方案,为WPF窗体程序添加一个Wpf自定义控件库CustomBtnLibrary。
首先我们定义的一个类我们叫它cButton,用依赖属性注册一个MouseOverBackground.
public class cButton : Button
{
public static readonly DependencyProperty MouseOverBackgroundProerty =
DependencyProperty.Register("MouseOverBackground",typeof(Brush),typeof(cButton),new PropertyMetadata(Brushes.RoyalBlue));
public Brush MouseOverBackground
{
get { return (Brush)GetValue(MouseOverBackgroundProerty); }
set { SetValue(MouseOverBackgroundProerty, value); }
}
static cButton()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(cButton), new FrameworkPropertyMetadata(typeof(cButton)));
}
}
打开Themes文件下的Generic.xaml
xmlns:local="clr-namespace:CustomBtnLibrary">添加命名空间
在Border标签下添加 ContenPresenter 为了显示内容,在ControlTemplate下添加 ControlTempleate.Triggers (Triggers事件触发器)
<ControlTemplate TargetType="{x:Type local:cButton}">
<Border x:Name="border"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="{Binding RelativeSource={RelativeSource Mode=TemplatedParent },Path=CornerRadius}">
<ContentPresenter x:Name="content" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
Content="{TemplateBinding Content}"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Mode=TemplatedParent},
Path=MouseOverBackground }" TargetName="border" />
</Trigger>
</ControlTemplate.Triggers>
在启动窗口MainWindow.xaml添加代码
添加命名空间
xmlns:local="clr-namespace:CustomBtnLibrary;assembly=CustomBtnLibrary"
<Grid>
<local:cButton Width="100" Height="40" CornerRadius="12" Background="#4000" PressedBackground="#8000" Content="哈哈"
Foreground="White" VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"/>
</Grid>
<local:cButton Width="100" Height="40" CornerRadius="12" Background="#4000" PressedBackground="#8000" Content="哈哈"
Foreground="White" VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"/>
</Grid>
来源:CSDN
作者:gd_linlong
链接:https://blog.csdn.net/qq_34539740/article/details/56670072