无法使用xaml中定义的控件在背后的代码中使用DataTemplate创建内容 [英] Can't create content with DataTemplate in code behind with control defined in xaml
问题描述
我在ContentPage的xaml中的ResourceDictionary中具有以下标签:
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);
}
}
在我的称为stack的StackLayout中-按下分配给Handle_Clicked的按钮时,仅添加1个标签.为什么只添加1个标签-应该添加3个标签?
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?
推荐答案
我怀疑所有控件都需要唯一的ID.由于这也不起作用:
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);
}
}
这使我首先尝试使用DataTemplate
.意味着同一对象只能添加到视图一次.
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.
还应注意,createContent()
是有效的-但前提是它是在xaml中定义的(未在后面的代码中实例化):
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>
我发现的解决方法是摆脱DataTemplate并在添加对象之前先克隆对象:
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);
}
}
这篇关于无法使用xaml中定义的控件在背后的代码中使用DataTemplate创建内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!