无法创建控制后面代码的DataTemplate内容在XAML定义(Can't create

2019-09-29 05:10发布

I have the following label in a ResourceDictionary in xaml of my ContentPage:

<ContentPage.Resources>
       <ResourceDictionary>
            <Label Text="I am label" x:Name="label" x:Key="label"/>
       </ResourceDictionary>
</ContentPaget.Resources>

And in in my code behind I have this clicked event handler:

void Handle_Clicked(object sender, System.EventArgs e)
    {
        DataTemplate dataTemplate = new DataTemplate(() => label);
        for (int i = 0; i < 3; i ++)
        {
            Label content = (Label) dataTemplate.CreateContent();
            stack.Children.Add(content);
        }
    }

In my StackLayout called stack - only 1 label is added when the button assigned with Handle_Clicked is pressed. Why is only 1 label added - when there should be 3 labels added?

Answer 1:

我怀疑所有的控制需要一个唯一的ID。 因为这是不工作之一:

void Handle_Clicked(object sender, System.EventArgs e)
{
    for (int i = 0; i < 3; i ++)
    {
        stack.Children.Add(label);
    }
}

这给我带来了尝试和使用DataTemplate位居第一。 义同对象只能一次添加到视图。

它也可以指出的是, createContent()的作品-但只有当它是在XAML中被定义(而不是在代码中实例化后):

<ContentPage.Resources>
       <ResourceDictionary>
            <DataTemplate x:Name="dataTemplate" x:Key="dataTemplate">
                <Label Text="I am label"/>
            </DataTemplate>
       </ResourceDictionary>
</ContentPaget.Resources>

我找到了解决方法是摆脱的DataTemplate和克隆添加它之前,而不是对象:

void Handle_Clicked(object sender, System.EventArgs e)
{
    for (int i = 0; i < 3; i ++)
    {
        var l = FastDeepCloner.DeepCloner.Clone(label);
        stack.Children.Add(l);
    }
}


文章来源: Can't create content with DataTemplate in code behind with control defined in xaml