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

显示效果,

相关推荐
hqwest7 小时前
C#WPF实战出真汁08--【消费开单】--餐桌面板展示
c#·wpf·ui设计·wpf界面设计
orangapple7 小时前
WPF 打印报告图片大小的自适应(含完整示例与详解)
c#·wpf
三千道应用题1 天前
WPF&C#超市管理系统(6)订单详情、顾客注册、商品销售排行查询和库存提示、LiveChat报表
开发语言·c#·wpf
✎ ﹏梦醒͜ღ҉繁华落℘2 天前
开发WPF项目时遇到的问题总结
wpf
hqwest3 天前
C#WPF实战出真汁06--【系统设置】--餐桌类型设置
c#·.net·wpf·布局·分页·命令·viewmodel
Vae_Mars3 天前
WPF中使用InputBindings进行快捷键绑定
wpf
hqwest3 天前
C#WPF实战出真汁05--左侧导航
开发语言·c#·wpf·主界面·窗体设计·视图viewmodel
hqwest3 天前
C#WPF实战出真汁01--项目介绍
开发语言·c#·wpf
wuty0074 天前
WPF 实现支持动态调整高度的文本显示控件
wpf·scrollviewer·extentheight·自动高度控件·动态调整高度
范纹杉想快点毕业7 天前
C 语言主控开发与显控开发能力体系及技术栈详解,STM32、QT、嵌入式、边缘系统显示
stm32·单片机·tcp/ip·microsoft·fpga开发·51单片机·wpf