6

オブジェクトをコンテンツコントロールに割り当てると、割り当てられたオブジェクトに適したビジュアルが実現されます。同じ結果を達成するためのプログラム的な方法はありますか?オブジェクトを使用してWPFの関数を呼び出し、ビジュアルを取得します。ここでは、オブジェクトをコンテンツコントロールインスタンスに提供した場合と同じロジックがビジュアルの生成に適用されます。

たとえば、POCOオブジェクトがあり、それをContentコントロールに割り当て、適切なDataTemplateが定義されている場合、そのテンプレートをマテリアライズしてビジュアルを作成します。コードでPOCOオブジェクトを取得し、WPFtheVisualから取得できるようにしたいと思います。

何か案は?

4

1 に答える 1

9

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;
}
于 2011-08-23T04:09:27.293 に答える