WPF ControlTemplate 控件模板

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

演示,

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

csharp 复制代码
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)));
    }
}

前端设置 ControlTemplate,

xml 复制代码
<UserControl.Resources>

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

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

xml 复制代码
<local:MyControl
    Width="200"
    Height="40"
    MyProperty="我是自定义控件~" />

显示效果,

相关推荐
happyprince15 小时前
07_verl-Trainer模块详解
人工智能·架构·wpf·强化学习
bugcome_com18 小时前
WPF + Prism 技术指南与实战项目(二、模板搭建)
wpf
小满Autumn1 天前
log4net 日志框架 — 从配置到实战速查手册
笔记·c#·.net·wpf·上位机·log4net
政沅同学2 天前
基于 C# WPF + HALCON 的工业视觉算法工具框架(开源)
开发语言·c#·wpf
happyprince2 天前
03_verl-设计理念与核心原理
wpf
happyprince2 天前
01_verl-项目概览与架构总览
架构·wpf
Chris _data2 天前
# WPF 学习记录( 第二天)
学习·wpf
myenjoy_13 天前
大规模采集架构——从单台网关到千点集群
架构·wpf
Chris _data3 天前
c#学习WPF笔记(一)
学习·c#·wpf
FuckPatience4 天前
WPF 自定义容器控件的布局
wpf