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="我是自定义控件~" />

显示效果,

相关推荐
云中飞鸿16 小时前
该如何进行WPF界面设计
wpf
云中飞鸿2 天前
WPF分哪几块
wpf
newbe365242 天前
我们如何使用 impeccable 优化前端界面设计与实现稳定性
前端·人工智能·分布式·github·aigc·wpf
Chris _data20 天前
WPF 学习第三天 — Modbus RTU 串口通信
hadoop·学习·wpf
布吉岛的石头21 天前
Java 程序员第 43 阶段05:微服务整合大模型,跨服务调用架构设计实战,Seata分布式事务实战
wpf
步步为营DotNet21 天前
基于.NET Aspire 实现云原生应用的高效监控与可观测性
云原生·.net·wpf
芒鸽21 天前
HarmonyOS 分布式开发实战:设备协同、数据共享与跨设备迁移
分布式·wpf·harmonyos
Volunteer Technology21 天前
Flink状态管理与容错(二)
大数据·flink·wpf
happyprince22 天前
07_verl-Trainer模块详解
人工智能·架构·wpf·强化学习
bugcome_com22 天前
WPF + Prism 技术指南与实战项目(二、模板搭建)
wpf