2009-12-18 51 views
1

如果我有一個從System.Windows.DispatcherObject派生的對象,但定義了ControlTemplate通過綁定呈現非UIElement

public class A : System.Windows.DependencyObject 
{ 
    public ControlTemplate ControlTemplate {get; set;} 
} 

這是

public class B 
{ 
    public A NonUIElement {get; set;} 
} 

一個部件是否有可能通過結合諸如

<Border Name="Border"> 
<ContentPresenter Margin="5,0" Content="{Binding NonUIElement }"/> 
</Border> 

假定邊框的DataContext設置爲B的實例,以渲染該對象?

+0

是的,它應該工作,你試過嗎? – 2009-12-18 20:13:29

回答

3

該對象將呈現,但不是我認爲你所希望的方式。 ContentPresenterThe Content被設置爲A. WPF然後試圖弄清楚如何渲染這個A的實例。它首先詢問,這個對象是UIElement?在這種情況下,答案是否定的。所以它接下來尋找該類型的DataTemplate。在這種情況下,A類沒有DataTemplate。所以它回調ToString()。因此,您的ContentPresenter將顯示一個包含文本「YourNamespace.A」的TextBlock

A碰巧有ControlTemplate類型的成員不影響此邏輯。對於WPF來說,這只是一個數據而已,正好隨身攜帶。 WPF只有使用ControlTemplate當有涉及控制和ControlTemplate分配給Template屬性。

所以,你需要或者爲提供一個DataTemplate A(這當然可以訪問ControlTemplate,並用它來渲染實例),或者創建一個名爲DataTemplate並應用通過ContentPresenter.ContentTemplate,或從UIElement派生來代替。

+0

優秀的解釋,謝謝。但是,當你說我需要爲A提供一個DataTemplate時,我應該在哪裏分配我的HierarchicalDataTemplate,這正是我正在使用的? – 2009-12-18 21:59:43

+0

可能最簡單的方法是在ContentPresenter.ContentTemplate屬性上指定它:''。 – itowlson 2009-12-18 22:36:38

+0

如果在嘗試在您的建議中指定的ContentPresenter中呈現它之前,WPF使用將查找NonUIElement的ControlTemplate,爲什麼還需要提供DataTemplate? 不implicitley意思是「使用NonUEElement的ControlTemplate來渲染內容?」 – 2009-12-19 13:20:51

0

我終於明白了這一點;

<HierarchicalDataTemplate DataType="{x:Type vm:MapLayerModel}" ItemsSource="{Binding Path=Children, Mode=OneTime}"> 
**<ContentControl Margin="5" Content="{Binding LayerRepresentation}" Template="{Binding LayerRepresentation.ControlTemplate}" Mode=OneTime/>** 
</HierarchicalDataTemplate> 

這是一個關於WPF模板及其內容控制模型的很好的個人課程。再次感謝itowlson。