记录 | 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:创建。
相关推荐
自动化代码美学20 小时前
【Python3.13】官网学习之控制流
开发语言·windows·python·学习
AA陈超21 小时前
ASC学习笔记0020:用于定义角色或Actor的默认属性值
c++·笔记·学习·ue5·虚幻引擎
檐下翻书1731 天前
从入门到精通:流程图制作学习路径规划
论文阅读·人工智能·学习·算法·流程图·论文笔记
SalvoGao1 天前
Python学习 | 怎么理解epoch?
数据结构·人工智能·python·深度学习·学习
思成不止于此1 天前
深入理解 C++ 多态:从概念到实现的完整解析
开发语言·c++·笔记·学习·多态·c++40周年
Highcharts.js1 天前
学习 Highcharts 可视化开发的有效途径
学习·数据可视化·highcharts·图表开发·可视化开发
胡童嘉1 天前
长沙烈焰鸟网络科技有限公司实习day12+软件测试学习day3日记
学习
5***a9751 天前
后端配置中心选型,Nacos与Apollo
wpf
·心猿意码·1 天前
WPF转换器机制
wpf
2501_941145851 天前
虚拟现实与增强现实技术在教育培训与沉浸式学习场景中的创新应用研究
学习·ar·vr