More on Triggers and Styles and Control Templates - Content Presenters
(Page 4 of 5 )
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 ourPlayerMoveobject. 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’sContent property is bound to theContentControl.Contentproperty so that content comes through. As with styles, we can avoid prefixing template binding property names with classes by setting theTargetType attribute on theContentTemplate element:
<ControlTemplate TargetType="{x:Type Button}">
<Grid>
<Rectangle Fill="{TemplateBinding Property=Background}" />
<ContentPresenter
Content="{TemplateBinding Property=Content}" />
</Grid>
</ControlTemplate>
Further, with theTargetType property in place, you can drop the explicit template binding on theContent 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 (Color Plate 14)
Next: The Real Work >>
More XML Articles
More By O'Reilly Media
|
This article is excerpted from chapter five of the book Programming Windows Presentation Foundation, written by Chris Sells and Ian Griffiths (O'Reilly; ISBN: 0596101139). Check it out today at your favorite bookstore. Buy this book now.
|
|