我想使用 get => ContentStack.Children 将子项添加到模板中;但这不能正常工作

问题描述

我有一个模板框架,它提供了一些填充并接受多个元素:

[Xamarin.Forms.contentproperty("Contents")]
public class ContentFrame : StackLayout
{
    public StackLayout ContentStack = new StackLayout();
    public IList<View> Contents { get => ContentStack.Children; }

    public ContentFrame()
    {
        CustomFrame cf = new CustomFrame()
        {
            Content = ContentStack,HasShadow = false,};
        cf.SetDynamicResource(BackgroundColorProperty,"ContentFrameBackgroundColor");
        cf.SetDynamicResource(Frame.CornerRadiusProperty,"ContentFrameCornerRadius");
        cf.SetDynamicResource(MarginProperty,"ContentFrameMargin");
        this.Children.Add(cf);
    }

我想添加这样的子标签:c1.Children.Add - 但是当我这样做时,BackgroundColor、CornerRadius 和 Margin 不会被使用(参见 ABC 和 ABC 图像的第一部分)

我可以让它使用这些的唯一方法是将 ContentStack 作为公共属性公开并添加到其中(参见下面的 ABC 和 GHI)

public class TestPage : headingView
{
    public TestPage() : base()
    {
        var s = new Stack();

        var c1 = new ContentFrame();
        c1.Children.Add(new Label() { Text = "ABC" });
        c1.Children.Add(new Label() { Text = "DEF" });

        var c2 = new ContentFrame();
        c2.ContentStack.Children.Add(new Label() { Text = "DEF" });
        c2.ContentStack.Children.Add(new Label() { Text = "GHI" });

        s.Children.Add(c1);
        s.Children.Add(c2);

        this.InnerContent = s;
    }
}

问题> 谁能解释为什么第一种情况(使用 get => ContentStack.Children)不显示框架背景、半径等。

enter image description here

解决方法

ContentStack 设为私有并添加一个方法来公开添加功能

private StackLayout ContentStack = new StackLayout();

public void Add(View view)
{
  this.ContentStack.Children.Add(view);
}

如果你想添加多个你也可以这样做

public void Add(List<View> views)
{
  foreach(var v in views) 
  {
    this.ContentStack.Children.Add(v);
  }
}