Reputation: 18857
If I have an object derived from System.Windows.DispatcherObject
but defines a ControlTemplate
.
public class A : System.Windows.DependencyObject
{
public ControlTemplate ControlTemplate {get; set;}
}
which is a member of
public class B
{
public A NonUIElement {get; set;}
}
Is it possible to render this object via a Binding such as
<Border Name="Border">
<ContentPresenter Margin="5,0" Content="{Binding NonUIElement }"/>
</Border>
assuming the DataContext
of border is set to an instance of B?
Upvotes: 1
Views: 652
Reputation: 74802
The object will render, but not in the way I think you're hoping for. The Content
of the ContentPresenter
is set to the instance of A. WPF then tries to figure out how to render this instance of A. It first asks, is this object a UIElement
? In this case, the answer is no. So it next looks for a DataTemplate
for the type. In this case, there's no DataTemplate
for the A class. So it falls back on calling ToString(). So your ContentPresenter
will display a TextBlock
containing the text "YourNamespace.A".
The fact that A happens to have a member of type ControlTemplate
does not affect this logic. To WPF, that's just a chunk of data that A happens to be carrying around. WPF only uses ControlTemplate
when there is a Control involved and the ControlTemplate
is assigned to the Template
property.
So you need either to supply a DataTemplate
for A (which of course can access the ControlTemplate
and use it to render the instance), or create a named DataTemplate
and apply that via ContentPresenter.ContentTemplate
, or derive from UIElement
instead.
Upvotes: 3
Reputation: 18857
I finally got it with this;
<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>
This has been a great personal lesson on WPF templating and its content control model. Thanks again itowlson.
Upvotes: 0