Reputation: 601
In .NET/WP/WPF, I am looking to create my first user control that will render content using a DataTemplate and am wondering how to do that. Do I need to use the Content presenter and pass it a reference to the template or what? Thanks for the help guys!
Upvotes: 1
Views: 1001
Reputation: 24453
The basic strategy for including templated content in other fixed content (like the XAML of a UserControl
) is to define a set of Content
properties (as DependencyProperties
) on the containing control and then add a ContentPresenter
(with appropriate bindings) as the placeholder into which the content will be injected. In the framework you can see an example of this in HeaderedContentControl
which has both a normal Content
property set, but also a parallel set of Header
properties that are used as a second piece of content.
The properties you can define on your control (differing by platform) are:
Content
ContentTemplate
ContentTemplateSelector
ContentStringFormat
with whatever your custom name is substituted for "Content" in each. In your case you probably only have the first two. Then in your UserControl
layout (which is actually defining the Content itself of the UserControl
) just place a ContentPresenter
and set it up to use your custom properties with the control itself as the Binding Source
(ElementName
, RelativeSource
, or setting the DataContext
somewhere to the UserControl
itself):
<ContentPresenter Content="{Binding ElementName=MyControl, Path=MyExtraContent}"
ContentTemplate="{Binding ElementName=MyControl, Path=MyExtraContentTemplate}" />
In most cases (but not here) ContentPresenter
is used inside a ControlTemplate
where you can use a nice shortcut that's built in to bind all the content properties for you:
<ContentPresenter ContentSource="MyExtraContent"/>
You can get the same effect with ContentControl
but it's adding extra elements to your visual tree since it's basically just a ContentTemplate
containing a ContentPresenter
that passes all the properties through. It does allow you to add some visual differences, like Background
or Padding
, or add a whole custom template but in cases like this you can do exactly the same thing by just adding other controls around your ContentPresenter
.
Upvotes: 4