记录 | 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:创建。
相关推荐
通信小呆呆11 小时前
当算法有了“五感”:多模态数据融合如何向人体感官协同学习?
人工智能·学习·算法·机器学习·机器人
H__Rick11 小时前
自动对焦学习-3
人工智能·学习·计算机视觉
Daisy Lee11 小时前
量化学习-第1章-什么是量化金融
学习·金融·datawhale
Alsn8612 小时前
等待学习-学习目录:Docker 容器安全攻防
学习·安全·docker
YM52e12 小时前
买菜计算器小应用 - HarmonyOS ArkUI 开发实战-PC版本
学习·华为·harmonyos·鸿蒙·鸿蒙系统
小雨下雨的雨12 小时前
HarmonyOS ArkUI训练营入门-组件掌握系列-Animation 动画效果实现-PC版本
学习·华为·harmonyos·鸿蒙
cqbzcsq13 小时前
CellFlow虚拟细胞论文阅读
论文阅读·人工智能·笔记·学习·生物信息
YangYang9YangYan14 小时前
2026初入职场学习数据分析的价值
学习·数据挖掘·数据分析
guslegend15 小时前
理论学习:什么是 Coding Agent?
学习
自传.15 小时前
尚硅谷 Vibe Coding|第三章(1) Claude Code深度使用与进阶技巧 学习笔记
笔记·学习·尚硅谷·vibecoding