2010-05-05 43 views
0

我已经在XAML中定义了DataTemplate,但是我需要将它更改为在运行时定义,因为它的绑定是动态的。如何在运行时创建DataTemplate?

<UserControl.Resources> 
    <DataTemplate x:Key="myCellTemplate"> 
    <TextBlock Text="{Binding Description}" Margin="4"/> 
    </DataTemplate> 
</UserControl.Resources> 

有什么方法可以在代码隐藏中定义它吗? 谢谢。

+0

[在代码中创建Silverlight DataTemplate]的可能重复(http://stackoverflow.com/questions/59451/creating-a-silverlight-datatemplate-in-code) – 2014-07-29 03:59:57

回答

1

您可能可以通过自定义DataTemplateSelector来完成您所需的工作,如果可能的话,我会建议您使用此方法。这就是说,它是可能的代码来创建一个DataTemplate:

Type type = typeof(MyUserControl); //for example  
var template = new DataTemplate(); 
template.VisualTree = new FrameworkElementFactory(type); 
return template; 

在此背景下,type是你想有作为模板的根视觉元素的类型。如果需要,可以使用工厂添加其他元素,但在使用此工具的一种情况下,我只是创建UserControl元素来表示我动态创建的不同模板。


我的歉意,这显然不支持在Silverlight中。在Silverlight中,您必须使用XamlReader

+1

谢谢。我正在使用Silverlight 3,但无法找到FrameworkElementFactory – Naseem 2010-05-05 01:42:10

+0

谢谢。关于你的回答: http://stackoverflow.com/questions/59451/creating-a-silverlight-datatemplate-in-code – Naseem 2010-05-05 03:24:38