wpf自定义按钮样式

在WPF中,自定义按钮样式可以通过创建一个ControlTemplate来实现。以下是一个简单的自定义按钮样式的例子:

首先,在你的WPF项目资源字典中定义按钮的ControlTemplate

复制代码
<Window.Resources>
    <ControlTemplate x:Key="CustomButtonTemplate" TargetType="Button">
        <Border Name="border" BorderBrush="{TemplateBinding BorderBrush}" 
                BorderThickness="{TemplateBinding BorderThickness}" 
                Background="{TemplateBinding Background}" 
                SnapsToDevicePixels="true">
            <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" 
                              VerticalAlignment="{TemplateBinding VerticalContentAlignment}" 
                              SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
        </Border>
        <ControlTemplate.Triggers>
            <Trigger Property="IsMouseOver" Value="true">
                <Setter TargetName="border" Property="Background" Value="LightBlue"/>
            </Trigger>
            <Trigger Property="IsPressed" Value="true">
                <Setter TargetName="border" Property="Background" Value="DarkBlue"/>
            </Trigger>
        </ControlTemplate.Triggers>
    </ControlTemplate>
</Window.Resources>

然后,你可以将这个模板应用到你的按钮上:

复制代码
<Button Content="Click Me" Template="{StaticResource CustomButtonTemplate}" 
        Width="100" Height="30" />

这个例子中的按钮模板包括一个Border来定义按钮的外观,以及ControlTemplate.Triggers来定义当鼠标悬停和按钮被按下时的视觉变化。你可以根据需要自定义ControlTemplate的内容和行为。

说明:

鼠标悬停 效果

<Trigger Property="IsMouseOver" Value="true">

修改border元素的背景色为LightBlue

<Setter TargetName="border" Property="Background" Value="LightBlue"/>

按钮被按下时

<Trigger Property="IsPressed" Value="true">

修改border元素的背景色为DarkBlue

相关推荐
玖笙&8 小时前
✨WPF编程基础【3.3】:容器控件(附源码)
c++·wpf·visual studio
5008414 小时前
GE 怎么做算子融合
分布式·架构·开源·wpf
500841 天前
Conv + BN + ReLU 融合:省掉两次显存读写
flutter·架构·开源·wpf·音视频
500841 天前
把 FlashAttention 讲清楚
flutter·electron·wpf
500841 天前
ATC 做了什么:从 ONNX 到 .om
分布式·架构·开源·wpf·开源鸿蒙
500842 天前
Graph Engine 是什么,为什么需要它
java·人工智能·性能优化·ocr·wpf
一念春风2 天前
.md文件浏览器
c#·wpf
lingxiao168882 天前
Wpf常用样式与自定义控件(仪表盘,管道,分页器等)
wpf
LateFrames2 天前
520 - 如何说晚安 (WPF)
c#·wpf·浪漫·ui体验
heimeiyingwang3 天前
【架构实战】日志体系ELK:集中化日志管理实践
elk·架构·wpf