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>
相关推荐
明耀15 小时前
WPF DataGrid 默认显示行号
wpf
lph197219 小时前
wpf的converter
wpf
fyifei055819 小时前
WPF学习PropertyChanged
wpf
爱炸薯条的小朋友19 小时前
C#由于获取WPF窗口名称造成的异常报错问题
windows·c#·wpf
baivfhpwxf202319 小时前
wpf ListBox 去除item 单击样式
wpf
诗仙&李白19 小时前
lnnovationHubTool,用prism+WPF编写的MVVM模式的快速上位机软件开发框架平台
wpf·mvvm·prism·上位机软件开发框架平台
程序员小刘1 天前
【HarmonyOS 5】教育开发实践详解以及详细代码案例
华为·wpf·harmonyos
Java Fans2 天前
在WPF项目中集成Python:Python.NET深度实战指南
python·.net·wpf
布伦鸽2 天前
C# WPF 左右布局实现学习笔记(1)
笔记·学习·c#·wpf
code bean3 天前
【WPF】WPF 项目实战:构建一个可增删、排序的光源类型管理界面(含源码)
wpf