Can't create content with DataTemplate in code behind with control defined in xaml

血红的双手。 提交于 2019-12-11 06:47:58

问题


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?


回答1:


I suspect that all controls need a unique id. Since this was not working either:

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

which had brought me to try and use DataTemplate in the first place. Meaning the same object can only be added once to the view.

It can also be noted that createContent() works - but only if it is being defined in xaml (not being instantiated in code behind):

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

The workaround I found was to get rid of the DataTemplate and clone the object instead before adding it:

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);
    }
}


来源:https://stackoverflow.com/questions/56405488/cant-create-content-with-datatemplate-in-code-behind-with-control-defined-in-xa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!