WPF - 如何以编程方式将对象实现为可视内容?

Phi*_*ght 6 wpf contentpresenter contentcontrol

将对象分配给Content控件时,它将实现适合该已分配对象的Visual.有没有一种程序化的方法来实现相同的结果?我想在WPF中使用一个对象调用一个函数并返回一个Visual,其中在生成Visual时应用相同的逻辑,就像您已将对象提供给Content控件实例一样.

例如,如果我有一个POCO对象并将其分配给Content控件并且恰好定义了相应的DataTemplate,那么它将实现该模板以创建Visual.我希望我的代码能够获取POCO对象并从WPF中获取Visual.

有任何想法吗?

Har*_*ess 9

使用DataTemplate.LoadContent().例:

DataTemplate dataTemplate = this.Resources["MyDataTemplate"] as DataTemplate;
FrameworkElement frameworkElement = dataTemplate.LoadContent() as FrameworkElement;
frameworkElement.DataContext = myPOCOInstance;

LayoutRoot.Children.Add(frameworkElement);
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)