WPF Styles and Control Templates—Content Presenters
| Visual C# Tutorials |
| .NET Framework Tutorials |
| © 2005 O'Reilly Media |
Content Presenters
If you’ve ever driven by a billboard or a bench at a bus stop that says "Your advertisement
here!" then that’s all you need to know to understand content presenters. A content presenter is the WPF equivalent of "your content here" that allows content
held by a ContentContainer control to be plugged in at runtime.
In our case, the content is the visualization of our PlayerMove object. Instead of
reproducing all of that work inside of the button’s new control template, we’d just
like to drop it in at the right spot. The job of the content presenter is to take the content
provided by the templated parent and do all of the things necessary to get it to
show up properly, including styles, triggers, etc. The content presenter itself can be
dropped into your template wherever you’d like to see it (including multiple times, if
it tickles your fancy—e.g., to produce a drop shadow). In our case, we’ll compose a
content presenter in Example 5-34 with the rectangle inside a grid using techniques
from Chapter 2.
Example 5-34. A content presenter
<Style TargetType="{x:Type Button}"> <Setter Property="Background" Value="White" /> ... <Setter Property="Template"> <Setter.Value> <ControlTemplate> <Grid> <Rectangle Fill="{TemplateBinding Property=Background}" /> <ContentPresenter Content="{TemplateBinding Property=ContentControl.Content}" /> </Grid> </ControlTemplate> </Setter.Value> </Setter> ... </Style>
In Example 5-34, the content presenter’s Content property is bound to the
ContentControl.Content property so that content comes through. As with styles, we
can avoid prefixing template binding property names with classes by setting the
TargetType attribute on the ContentTemplate element:
<ControlTemplate TargetType="{x:Type Button}"> <Grid> <Rectangle Fill="{TemplateBinding Property=Background}" /> <ContentPresenter Content="{TemplateBinding Property=Content}" /> </Grid> </ControlTemplate>
Further, with the TargetType property in place, you can drop the explicit template
binding on the Content property altogether, as it’s now set automatically:
<ControlTemplate TargetType="{x:Type Button}"> <Grid> <Rectangle Fill="{TemplateBinding Property=Background}" /> <!-- with TargetType set, the template binding for the --> !-- Content property is no longer required --> <ContentPresenter /> </Grid> </ControlTemplate>
The content presenter is all we need to get our game back to being functional, as shown in Figure 5-19.

Figure 5-19. Adding a content presenter to our control template
|

