What's the difference between ContentControl and ContentPresenter?
ContentControl
is a base class for controls that contain other elements and have a Content
-property (for example, Button
).
ContentPresenter
is used inside control templates to display content.
ContentControl
, when used directly (it's supposed to be used as a base class), has a control template that uses ContentPresenter to display it's content.
My rules of thumb (not applicable in every case, use your judgment):
- Inside
ControlTemplate
useContentPresenter
- Outside of
ControlTemplate
(includingDataTemplate
and outside templates) try not to use any of them, if you need to, you must preferContentPresenter
- Subclass
ContentControl
if you are creating a custom "lookless" control that host content and you can't get the same result by changing an existing control's template (that should be extremely rare).
ContentPresenter is usually used in a ControlTemplate, as a placeholder to say "put the actual content here".
A ContentControl can be used anywhere, not necessarily in a template. It will pick up any DataTemplate defined for the type of content assigned to it
I recently wrote a post on my blog regarding these two controls:
ContentPresenter vs ContentControl
The ContentPresenter.ContentSource is what actually makes the biggest difference between the two classes.
ContentSource property makes sense only within a ControlTemplate; it determines which TemplatedParent property the content should be mapped with.
For example, if a control contains a dependency property MyProperty1
, then we might find the following within its ControlTemplate
:
<ControlTemplate TargetType="MyControl" >
[...]
<ContentPresenter ContentSource="MyProperty1" />
[...]
</ControlTemplate>
The content of the ContentPresenter will receive the value of MyProperty1
.
Please note that if the name of the property is Content
, there is no need to specify ContentSource
as it is the default value.
For those who know angularJs: this is similar to transclude mecanism.