concept ContentPresenter in category silverlight

appears as: ContentPresenter, The ContentPresenter
Silverlight 4 in Action: Silverlight 4, MVVM, and WCF RIA Services

This is an excerpt from Manning's book Silverlight 4 in Action: Silverlight 4, MVVM, and WCF RIA Services.

The ContentPresenter is a descendent FrameworkElement that exists primarily to support the display of content in a ContentControl. Rather than require you to put a TextBlock, Image, or other strongly typed content presentation element into your control template, you can use a ContentPresenter to bind to and display the content from the Content property.

Table 10.7 shows the properties of the ContentPresenter element.

Table 10.7. Properties for the ContentPresenter element

Member

Description

Content The value assigned from the same property of a ContentControl
ContentTemplate The template value assigned from the same property of a ContentControl

Without the ContentPresenter, the ContentControl can’t do much of anything exciting. The ContentPresenter holds the logic to try and render the object passed into it. In fact, in a typical control template, the ContentPresenter simply is assigned values from the ContentControl via template binding, as seen here:

<ContentPresenter
Content="{TemplateBinding Content}"
Margin="{TemplateBinding Padding}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />

We’ll cover TemplateBinding in chapter 23 when we work with control templates. For now, understand that TemplateBinding is used to bind an element in XAML to a dependency property in the control’s implementation. For example, the Content property of the ContentPresenter in the preceding code is bound to the Content property of the containing ContentControl.

Together, Controls, ContentControls, and the associated ContentPresenter make up the core of the control tree in Silverlight. One other type of control, the ItemsControl, is equally as important. But before we look at the various types of ItemsControls, let’s look at some concrete implementations of ContentControls—specifically, those based on Button.

You may have noticed that the Content of the Button elements in the past two listings hasn’t been shown because, when you define a ControlTemplate, you must tell Silverlight where to place that Content. To help you do this task, Silverlight provides two FrameworkElement instances: ContentPresenter and ItemsPresenter.

The ContentPresenter class empowers you to specify where the Content of a ContentControl should be shown. It may be easiest to think of this element as a placeholder for some piece of Content. Beyond that, the syntax of a ContentPresenter is the element itself, as shown in listing 23.15.