使用 DataTemplate.LoadContent()。例子:
DataTemplate dataTemplate = this.Resources["MyDataTemplate"] as DataTemplate;
FrameworkElement frameworkElement = dataTemplate.LoadContent() as FrameworkElement;
frameworkElement.DataContext = myPOCOInstance;
LayoutRoot.Children.Add(frameworkElement);
http://msdn.microsoft.com/en-us/library/system.windows.frameworktemplate.loadcontent.aspx
如果您为某个类型的所有实例定义了 DataTemplate(DataType={x:Type ...},但没有 x:Key="..."),那么您可以使用以下静态方法使用适当的 DataTemplate 创建内容. 如果未找到 DataTemplate,此方法还通过返回 TextBlock 来模拟 ContentControl。
/// <summary>
/// Create content for an object based on a DataType scoped DataTemplate
/// </summary>
/// <param name="sourceObject">Object to create the content from</param>
/// <param name="resourceDictionary">ResourceDictionary to search for the DataTemplate</param>
/// <returns>Returns the root element of the content</returns>
public static FrameworkElement CreateFrameworkElementFromObject(object sourceObject, ResourceDictionary resourceDictionary)
{
// Find a DataTemplate defined for the DataType
DataTemplate dataTemplate = resourceDictionary[new DataTemplateKey(sourceObject.GetType())] as DataTemplate;
if (dataTemplate != null)
{
// Load the content for the DataTemplate
FrameworkElement frameworkElement = dataTemplate.LoadContent() as FrameworkElement;
// Set the DataContext of the loaded content to the supplied object
frameworkElement.DataContext = sourceObject;
// Return the content
return frameworkElement;
}
// Return a TextBlock if no DataTemplate is found for the source object data type
TextBlock textBlock = new TextBlock();
Binding binding = new Binding(String.Empty);
binding.Source = sourceObject;
textBlock.SetBinding(TextBlock.TextProperty, binding);
return textBlock;
}