自定义布局与标记的孩子

时间:2017-07-24 10:58:32

标签: c# xaml xamarin xamarin.forms

更新:似乎TableView提供了许多我正在寻找的功能。

原始问题:
我有一个自定义布局(StackLayout作为基础),其中包含一个子列表。对于每个孩子,我想添加一个标签 - xaml可能看起来像这样:

<ContentList>
  <Entry ContentList.Header="Entry 01" Placeholder="Text here"/>
  <Entry ContentList.Header="Entry 02" Placeholder="Text here"/>
</ContentList>

哪会导致:

<ContentList>
  <Label Text="Entry 01"/>
  <Entry Placeholder="Text here"/>
  <Label Text="Entry 02"/>
  <Entry Placeholder="Text here"/>
</ContentList>

到目前为止,我已根据StackLayout创建了布局,并且可以正常添加子项,但我在解决如何应用其他标签方面遇到了麻烦。我已经尝试重写OnChildAdded方法,但没有运气,也不确定接下来要尝试什么。

public partial class ContentList : StackLayout
{
    public static readonly BindableProperty HeaderProperty =
        BindableProperty.Create("Header", typeof(string), typeof(ContentList));

    public string Header
    {
        get { return (string)GetValue(HeaderProperty); }
        set
        {
            SetValue(HeaderProperty, value);
            OnPropertyChanged();
        }
    }

    public ContentList ()
    {
        InitializeComponent ();
    }

    private Label _label;
    protected override void OnChildAdded(Element child)
    {
        if (child != _label)
        {
            _label = new Label {Text = "LABEL"};
            Children.Add(_label);   // this causes an exception
        }

        base.OnChildAdded(child);
    }
}

也许最好的选择是使用[ContentProperty]指定一个新的视图集合并完全控制子项创建,但这似乎否定了将视图置于堆栈之外的有用性。

0 个答案:

没有答案