问题
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