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

显示效果,

相关推荐
界面开发小八哥19 小时前
界面组件DevExpress WPF中文教程:Grid - 如何显示和隐藏列?
wpf·界面控件·devexpress·ui开发·.net9
虚假程序设计20 小时前
python用 PythonNet 从 Python 调用 WPF 类库 UI 用XAML
python·ui·wpf
落落落sss1 天前
MongoDB
数据库·windows·redis·mongodb·微服务·wpf
蒋劲豪1 天前
WPF项目暴露WebApi接口;WinForm项目暴露WebApi接口;C#项目暴露WebApi接口;
开发语言·c#·wpf
狮歌~资深攻城狮2 天前
未来已来:HBase的新功能与发展趋势展望
大数据·wpf·hbase
界面开发小八哥2 天前
界面控件DevExpress WPF v24.2新版亮点:支持.NET 9
.net·wpf·界面控件·devexpress·ui开发·用户界面
九鼎科技-Leo3 天前
WPF快速创建DeepSeek本地自己的客户端-基础思路版本
wpf
MasterNeverDown4 天前
WPF 中为 Grid 设置背景图片全解析
大数据·hadoop·wpf
苏克贝塔4 天前
WPF8-常用控件
wpf
积跬步---行千里5 天前
记录一次WPF程序进程挂起问题
mongodb·wpf