记录 | WPF基础学习&自定义按钮

目录


前言

参考文章:

参考视频:【WPF入门教程 Visual Studio 2022】WPF界面开发入门

自己的感想

这里涉及到Template模板和事件。主要干两件事:1、template中的重写原button;2、添加鼠标悬浮和鼠标点击事件。


一、

csharp 复制代码
<Window x:Class="WPF_Study.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WPF_Study"
        mc:Ignorable="d"
        Title="WPF入门.txt" Height="600" Width="800">

    <Grid>
        <Button Width="300" Height="100" Content="自定义按钮" Background="Green" FontSize="50" Foreground="White">
        <!--自定义Button-->
            <Button.Template>
                <ControlTemplate TargetType="Button">
                    <Border x:Name="border" Background="{TemplateBinding Background}" BorderBrush="Black" BorderThickness="4" CornerRadius="10" HorizontalAlignment="Center" VerticalAlignment="Center">
                        <TextBlock x:Name="txtContent" Text="{TemplateBinding Content}"/>
                    </Border>
                    <!--自定义触发器-->
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter TargetName="border" Property="Background" Value="red"/>
                        </Trigger>
                        <Trigger Property="IsPressed" Value="true">
                            <Setter TargetName="txtContent" Property="TextBlock.Text" Value="已经点击"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Button.Template>
        </Button>
    </Grid>

</Window>

解析

Button.Template

Button.Template:通过 ControlTemplate 完全覆盖按钮的默认外观。

csharp 复制代码
<Grid>
    <Button Width="300" Height="100" Content="自定义按钮" 
            Background="Green" FontSize="50" Foreground="White">
        <!--自定义Button-->
        <Button.Template>
            <ControlTemplate TargetType="Button">
                <!-- 按钮模板内容 -->
            </ControlTemplate>
        </Button.Template>
    </Button>
</Grid>

Border和TemplateBinding

使用 Border 作为按钮容器,设置圆角、黑色边框。

内部通过 TextBlock 显示按钮内容(Content 属性)。

TemplateBinding:将按钮的 Background 和 Content 属性动态绑定到模板元素。

二、代码提供

点击下载


更新时间

  • 2025-02-06:创建。
相关推荐
vortex510 分钟前
新手上路之 NoSQL 数据库学习
数据库·学习·nosql
沉到海底去吧Go40 分钟前
【身份证识别表格】批量识别身份证扫描件或照片保存为Excel表格,怎么大批量将身份证图片转为excel表格?基于WPF和腾讯OCR的识别方案
ocr·wpf·excel·身份证识别表格·批量扫描件身份证转表格·图片识别表格·图片识别excel表格
MeiYu_1231 小时前
【数据结构与算法】图的基本概念与遍历
数据结构·c++·学习
虾球xz2 小时前
游戏引擎学习第270天:生成可行走的点
c++·学习·游戏引擎
吃货界的硬件攻城狮3 小时前
【STM32 学习笔记】USART串口
笔记·stm32·单片机·学习
XQ丶YTY3 小时前
记录一下学习kafka的使用以及思路
分布式·学习·kafka
吴爃3 小时前
linux搭建hadoop学习
linux·hadoop·学习
csdn_aspnet3 小时前
WPF 性能 UI 虚拟化 软件开发人员的思考
ui·wpf
海尔辛3 小时前
学习黑客Linux Flags and Switches 入门
linux·运维·学习
冰茶_4 小时前
WPF之绑定模式深入
学习·microsoft·微软·c#·wpf·绑定模式