当前位置: 首页 > news >正文

WPF ControlTemplate 控件模板

区别于 DataTemplate 数据模板,ControlTemplate 是控件模板,是为自定义控件的 Template 属性服务的,Template 属性类型就是 ControlTemplate。

演示,

自定义一个控件 MyControl,包含一个字符串类型的依赖属性。

public class MyControl : Control
{/// <summary>/// 获取或设置MyProperty的值/// </summary>  public string MyProperty{get => (string)GetValue(MyPropertyProperty);set => SetValue(MyPropertyProperty, value);}/// <summary>/// 标识 MyProperty 依赖属性。/// </summary>public static readonly DependencyProperty MyPropertyProperty =DependencyProperty.Register(nameof(MyProperty), typeof(string), typeof(MyControl), new PropertyMetadata(default(string)));static MyControl(){DefaultStyleKeyProperty.OverrideMetadata(typeof(MyControl), new FrameworkPropertyMetadata(typeof(MyControl)));}
}

前端样式中设置一下 Template 属性,它的值即 ControlTemplate,

<UserControl.Resources><Style TargetType="{x:Type local:MyControl}"><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="{x:Type local:MyControl}"><Grid Background="DeepPink"><TextBlockHorizontalAlignment="Center"VerticalAlignment="Center"Text="{TemplateBinding MyProperty}" /></Grid></ControlTemplate></Setter.Value></Setter></Style></UserControl.Resources>

使用这个自定义控件,设置其 MyProperty 属性值,

<local:MyControlWidth="200"Height="40"MyProperty="我是自定义控件~" />

显示效果,
在这里插入图片描述

http://www.lryc.cn/news/507414.html

相关文章:

  • 序列化和反序列化(一)
  • Kubeadm+Containerd部署k8s(v1.28.2)集群(非高可用版)
  • 取子串(指针)
  • Linux系列之如何更换Centos yum源?
  • 过滤器和拦截器的区别详解
  • centos使用mkisofs构建无人值守镜像(附官方学习文档)
  • Pyside6+qml+Qtcreator项目实战
  • 秒鲨后端之MyBatis【1】环境的搭建和核心配置文件详解
  • 编译原理复习---目标代码生成
  • Winnows基础(2)
  • 酒蒙子骰子小程序系统
  • 网络安全防范
  • 重拾设计模式--组合模式
  • 红米Note 9 Pro5G刷小米官方系统
  • 渗透测试-前端加密分析之RSA加密登录(密钥来源服务器)
  • 踩准智能汽车+机器人两大风口,速腾聚创AI+机器人应用双线爆发
  • YOLOv8全解析:高效、精准的目标检测新时代——创新架构与性能提升
  • 【Python】使用Selenium 操作浏览器 自动化测试 记录
  • GDPU软件工程习题(挖空版)
  • 【活动邀请·深圳】深圳COC社区 深圳 AWS UG 2024 re:Invent re:Cap
  • Hutool工具包的常用工具类的使用介绍
  • C++简明教程(文章要求学过一点C语言)(2)
  • 防火墙技术与网络安全
  • html 中 表格和表单的关系与区别
  • 基于Java的购物网站毕业论文
  • Redis——缓存预热+缓存雪崩+缓存击穿+缓存穿透
  • wxWidgets使用wxStyledTextCtrl(Scintilla编辑器)的正确姿势
  • 【ETCD】【实操篇(二)】如何从源码编译并在window上搭建etcd集群?
  • 服务器数据恢复—V7000存储中多块磁盘出现故障导致业务中断的数据恢复案例
  • 冯诺依曼架构与哈佛架构的对比与应用