我可以将 Xaml <Label> 组合到用于创建框架的 C# 模板中吗?

Can I combine a Xaml <Label> into a C# template that I use to create a Frame?

我有 XAML 用于设置框架和框架标题的代码,如下所示:

<Label Text="ABC" />
<t:ContentFrame>
   <Label Text="ABC" />
</t:ContentFrame>

对于 ContentFrame 我在这里使用 C# 模板:

[Xamarin.Forms.ContentProperty("Contents")]
public class ContentFrame : CustomFrame
{
    StackLayout contentStack { get; } = new StackLayout()
    {
        Spacing = 0,
        Padding = new Thickness(0),
        Orientation = StackOrientation.Vertical
    };
    public IList<View> Contents { get => contentStack.Children; }

    public ContentFrame()
    {
        Content = contentStack;
        HasShadow = false;
        SetDynamicResource(BackgroundColorProperty, "ContentFrameBackgroundColor");
        SetDynamicResource(BorderColorProperty, "ContentFrameBorderColor");
        SetDynamicResource(CornerRadiusProperty, "ContentFrameCornerRadius");
    }
}

有没有一种方法可以将标题的设置合并到 ContentFrame class 中,这样可以通过以下方式实现同​​样的效果:

<t:ContentFrame Heading="ABC">
   <Label Text="ABC" />
</t:ContentFrame>

为此你需要 Bindable property:

public class ContentFrame : CustomFrame
{
StackLayout contentStack { get; } = new StackLayout()
    {
        Spacing = 0,
        Padding = new Thickness(0),
        Orientation = StackOrientation.Vertical
    };
    public IList<View> Contents { get => contentStack.Children; }
    public static readonly BindableProperty HeadingProperty =
            BindableProperty.Create(nameof(Heading), typeof(string),
            typeof(ContentFrame), null, propertyChanged: OnHeadingChanged);

    public string Heading
    {
        get => (Heading)GetValue(HeadingProperty);
        set => SetValue(HeadingProperty, value);
    }

static void OnHeadingChanged(BindableObject bindable, object oldValue, object newValue) {
//whatever you want to handle
 }

    public ContentFrame()
    {
        Content = contentStack;
        HasShadow = false;
        SetDynamicResource(BackgroundColorProperty, "ContentFrameBackgroundColor");
        SetDynamicResource(BorderColorProperty, "ContentFrameBorderColor");
        SetDynamicResource(CornerRadiusProperty, "ContentFrameCornerRadius");
    }
}

如果您不需要 InotifypropertyChanged,您可以删除 OnHeadingChanged(也可以从 BindableProperty.Create() 中删除,如果需要,您可以添加以下声明。