班级上方的“[Xamarin.Forms.ContentProperty("Contents")]”实际上在做什么?

问题描述

我理解这段代码的工作原理,但有人能解释一下第一行的作用吗?这是否将某个地方翻译成一些 C# 代码。如果我想手动编写代码,我该怎么做?

[Xamarin.Forms.contentproperty("Contents")]
class PopupFrame : Frame
{
    StackLayout contentStack { get; } = new StackLayout();

    public IList<View> Contents { get => contentStack.Children; }


    public PopupFrame()
    {
        Content = contentStack;

        HasShadow = true;
        HorizontalOptions = Layoutoptions.FillAndExpand;
        Padding = 0;
        VerticalOptions = Layoutoptions.Center;
    }
}

解决方法

这个属性告诉 XAML 处理器,如果应该使用 FrameContent 属性作为默认值。所以,在实践中它允许你写这个

<ContentView>
    <Label Text="Hello,Forms"/>
</ContentView>

代替

<ContentView>
    <ContentView.Content>
       <Label Text="Hello,Forms"/>
    </ContentView.Content>
</ContentView>

取自 Docs page 的示例。

关于你的问题“我如何用 C# 编写这个?”你没有。这是 XAML 特有的东西,只不过是语法糖。在 C# 中,您只需将某些内容分配给 Content 属性。即:

var frame = new Frame();

Frame.Content = new Label() { Text = "Hello,Forms" };