WPF:自定义按钮模板

1.WPF:自定义按钮模板

自定义封装的按钮属性可写在<Button.Template>中

Background="{TemplateBinding Background}"中的TemplateBinding代表使用按钮本身所使用的背景颜色 不在样式内修改背景颜色

例如:

csharp 复制代码
 <Button Width="300" Height="100" Content="自定义按钮" Background="Bisque" FontSize="23" Foreground="Orchid">
            <Button.Template>
                <ControlTemplate TargetType="{x:Type Button}">//代表指向的button按钮
                    <Border Background="{TemplateBinding Background}"  BorderBrush="Black" BorderThickness="4" CornerRadius="10">
                        <ContentPresenter HorizontalAlignment="Center" Content="14321412535" VerticalAlignment="Center"></ContentPresenter>    
                    </Border>
                    
                </ControlTemplate>
            </Button.Template>
        </Button>
2.通过事件处理改变属性

1.首先先定义按钮名称 <Border x:Name="button"

2.在 <ControlTemplate.Triggers>属性中写 <Trigger Property="IsMouseOver" value="True>写入通过什么触发事件

  1. <Setter TargetName="button" Property="Background" Value="black"/>根据TargetName找到对应的属性,并将其改变Property
csharp 复制代码
 <Button.Template>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Border x:Name="button" Background="{TemplateBinding Background}"  BorderBrush="Black" BorderThickness="4" CornerRadius="10">
          
                        <TextBlock Text="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="true">
                            <Setter TargetName="button" Property="Background" Value="black"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Button.Template>
相关推荐
gAlAxy...15 小时前
MyBatis 缓存深度解析(一级 / 二级缓存原理 + 实战 + 避坑)
wpf
泉飒1 天前
WinForm与WPF的异同点
wpf·winform
fireworkseasycold2 天前
wpf 基于 JSON 的扩展配置 (Extended Config)” 功能
oracle·json·wpf
脩衜者2 天前
极其灵活且敏捷的WPF组态控件ConPipe 2026
前端·物联网·ui·wpf
张人玉2 天前
西门子 S7 PLC 通信 WPF 应用分析笔记
笔记·c#·wpf·plc
张人玉2 天前
整合 Sugar ORM 连接 SQLite 数据库到 WPF 折线图项目
数据库·sqlite·c#·wpf
bugcome_com3 天前
WPF 中控件样式定义的三种方式详解
wpf
Psycho_MrZhang3 天前
Ray 设计思想总结
wpf
廋到被风吹走4 天前
【Spring】Spring AMQP 详细介绍
java·spring·wpf
kylezhao20195 天前
WinForm/WPF界面开发(常用控件、布局设计、事件处理)
大数据·hadoop·wpf