WPF: ContentControl vs ContentPresenter

A small post to explain the little but important difference between ContentControl and ContentPresenter.

The most significant difference is that ContentPresenter has the ContentSource property while ContentControl hasn’t.

The ContentPresenter.ContentSource property specify which dependency property of the parent template instnace should be used to fill the ContentPresenter.Content.

For instance if you have a UserControl “MyControl” that defines a dependency property called  “MyProperty”, you can use the value of MyControl.MyProperty in the MyControl.Template in this way:

<ControlTemplate TargetType="MyControl">
      <StackPanel>
          <ContentPresenter ContentSource="MyProperty" />
      </StackPanel>
</ControlTempalte>

Instead using the ContentControl you could write the same template in this way:

<ControlTemplate TargetType="MyControl">
      <StackPanel>
          <ContentControl Content="{TemplateBinding MyProperty}" />
      </StackPanel>
</ControlTempalte>

In fact the ContentControl has a template that uses a ContentPresenter to show it’s own Content property using the ContentSource. The ContentPresenter is a light-weight component that is supposed to be used in a template as a simple place-holder for the Content property. The default value for the ContentPresenter.ContentSource is “Content”, so you just need to add an empty ContentPresenter in a template to let be the place-holder of the Content property of the template parent instance.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s