2011-08-23 24 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作爲內容,請勿使用此方法。 –

相關問題