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>
相关推荐
张人玉5 小时前
C#WPF UI路由事件:事件冒泡与隧道机制
ui·c#·wpf
Aevget8 小时前
DevExpress WPF v25.2新功能预览 - 支持将JetBrains Rider与报表设计器集成
.net·wpf·界面控件·devexpress·ui开发
Aevget14 小时前
界面控件DevExpress WPF v25.1新版亮点:AI功能的全面升级
c#·.net·wpf·界面控件·devexpress·ui开发
beyond谚语2 天前
第一章 WPF概述
wpf
necessary6533 天前
从工行“余额归零”事件看CAP定理:当金融系统在一致性与可用性之间做出选择
分布式·金融·wpf·可用性测试
棉晗榜3 天前
WPF隐藏控件后,怎么让其上部的控件空间自动撑高
wpf
壹佰大多3 天前
【Redisson分布式锁源码分析-3】
数据结构·分布式·mysql·spring·spring cloud·wpf·lua
LateFrames4 天前
以小白视角尝试 WPF / WinUI3 / MAUI / MAUI Blazor 构建 Windows 桌面程序
windows·wpf·maui·mauiblazor·winui3
偶尔的鼠标人4 天前
Avalonia/WPF 打开子窗口,并且跨页面传值
c#·wpf·mvvm·avalonia
玖笙&4 天前
✨WPF编程进阶【6.1】:图形原则(附源码)
c++·c#·wpf·visual studio