WPF ControlTemplate 控件模板

发布于:2024-12-21 ⋅ 阅读:(193) ⋅ 点赞:(0)

区别于 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">
                        <TextBlock
                            HorizontalAlignment="Center"
                            VerticalAlignment="Center"
                            Text="{TemplateBinding MyProperty}" />
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    
</UserControl.Resources>

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

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

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


网站公告

今日签到

点亮在社区的每一天
去签到