将控件的XAML内容设置为该控件的属性

本文关键字:控件 属性 设置 XAML | 更新日期: 2023-09-27 17:49:25

我有一个这样的用户控件:

public partial class MyControl : UserControl
{
    private static readonly DependencyProperty pageContentProperty = DependencyProperty.Register("PageContent", typeof(UIElement), typeof(ActionPage), new PropertyMetadata(null));
    public UIElement PageContent
    {
        get { return (UIElement)base.GetValue(pageContentProperty); }
        set { base.SetValue(pageContentProperty, value); }
    }
    public MyControl()
    {
        InitializeComponent();
    }
    // More code
}

现在如果我在XAML中使用它我必须这样做:

<l:MyControl>
    <l:MyControl.PageContent>
         <TextBlock Text="Lorum Ipsum"/>
    </l:MyControl.PageContent>
</l:MyControl>

但是我只想做:

<l:MyControl>
    <TextBlock Text="Lorum Ipsum"/>
</l:MyControl>

目前,如果我这样做,它将用TextBlock(这对正常的UserControl有意义)替换控件的整个内容,但我如何才能覆盖此行为?

将控件的XAML内容设置为该控件的属性

您可以尝试将ContentProperty属性添加到您的PageContent属性:-

[ContentProperty("PageContent")]
public partial class MyControl : UserControl