2010-05-05 86 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