其他分享
首页 > 其他分享> > 控件作为依赖项属性/ WPF

控件作为依赖项属性/ WPF

作者:互联网

我有从Control类派生的自定义控件.我想创建另一个控件的依赖项属性(例如button),并将其放置在ControlTemplate中(这样,可以将按钮放置在xaml中,而MyControl的用户可以订阅其事件等).有人可以告诉我,我该怎么办?

这是结果代码示例:

public class MyControl: Control
{
    static MyControl( )
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(MyControl), new FrameworkPropertyMetadata(typeof(MyControl)));
    }

    public static readonly DependencyProperty MyButtonProperty =
        DependencyProperty.Register("MyButton",
                                    typeof(Button),
                                    typeof(MyControl),
                                    new PropertyMetadata(default(Button)));

    public Button MyButton
    {
        get
        {
            return (Button) GetValue(MyButtonProperty);
        }
        set
        {
            SetValue(MyButtonProperty, value);
        }
    }
}

xaml:

<ControlTemplate TargetType="{x:Type lib:MyControl}">
        <Canvas>
                <Border Child="{TemplateBinding MyButton}">
                </Border>
        </Canvas>
</ControlTemplate>

解决方法:

控件的模板可以通过TemplatePartAttribute声明对子控件的依赖.然后,您将在OnApplyTemplate方法中获得该依赖的实例.

[TemplatePart(Name = PartButton, Type = typeof(ButtonBase))]
public class MyControl : Control
{
    private const string PartButton = "PART_Button";
    private ButtonBase buttonPart;

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();

        this.buttonPart = GetTemplateChild(PartButton) as ButtonBase;
    }
}

您的控制模板将如下所示:

<Style TargetType="MyControl">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="MyControl">
                <Border ...>
                    <Button x:Name="PART_Button" .../>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style

请注意,如果模板中未包含适当命名的ButtonBase,则this.buttonPart可以为null.您应该努力确保缺少模板部件时控件仍然可以正常工作.

标签:wpf-controls,wpf,c
来源: https://codeday.me/bug/20191123/2066430.html