2011-08-23 17 views
6

当你分配对象的内容控制它一定会实现一个Visual适合该分配的对象。有没有一种程序化的方式来实现相同的结果?我想调用一个函数在WPF与对象,并得到一个视觉,在相同的逻辑是,如果你有供应对象的内容控件实例产生视觉应用。WPF - 如何以编程方式将对象实体化为可视内容?

例如,如果我有一个POCO对象并将其分配给一个内容控制和那里恰好是所定义的合适的DataTemplate则物化该模板来创建视觉。我希望我的代码能够获取POCO对象并从WPF中取回Visual。

任何想法?

回答

8

使用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(数据类型= {x:类型...},但没有X:键= “...”)那么您可以使用以下静态方法使用适当的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; 
} 
+0

我想要的东西,不正是因为内容类一样。即遵循与内容控制本身相同的逻辑。你的代码很好,对于DataTemplate场景来说可以。但是可能没有为我的POCO定义的DataTemplate。 –

+0

如果没有匹配的DataTemplate然后回落到创建一个TextBlock和POCO对象上使用的ToString()来定义的文本。 –

+0

足够简单,我只是更新了创建TextBox的方法,而不是在找不到DataTemplate的情况下返回null。仅供参考 - ContentControl将显示UIElement内容作为UIElement,因此如果您已经有UIElement作为内容,请勿使用此方法。 –

相关问题