记录 | 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:创建。
相关推荐
Scout-leaf3 天前
WPF新手村教程(三)—— 路由事件
c#·wpf
西岸行者5 天前
学习笔记:SKILLS 能帮助更好的vibe coding
笔记·学习
悠哉悠哉愿意5 天前
【单片机学习笔记】串口、超声波、NE555的同时使用
笔记·单片机·学习
别催小唐敲代码5 天前
嵌入式学习路线
学习
毛小茛5 天前
计算机系统概论——校验码
学习
babe小鑫5 天前
大专经济信息管理专业学习数据分析的必要性
学习·数据挖掘·数据分析
winfreedoms5 天前
ROS2知识大白话
笔记·学习·ros2
在这habit之下5 天前
Linux Virtual Server(LVS)学习总结
linux·学习·lvs
我想我不够好。5 天前
2026.2.25监控学习
学习
im_AMBER5 天前
Leetcode 127 删除有序数组中的重复项 | 删除有序数组中的重复项 II
数据结构·学习·算法·leetcode