Presenting the ContentPresenter
A template contains an arrangement of controls that make up some other control. Defining the controls themselves isn't difficult, but there are a couple pieces of information that you cannot hardwire directly into the template's code.
First, the template cannot directly include whatever it is that the control is supposed to display. For example, suppose you're building a Label template. You can use a TextBlock or some other control (even a regular Label) to define the control, but you cannot hard-code the value the Label will display. (If you were to set the TextBlock's Text property to "Hello," the control wouldn't be able to display anything other than "Hello.")
WPF provides a ContentPresenter object to tell the template what the control is supposed to display. You place this object inside the template where you want the content displayed and WPF does its best to do the rest.
With that little bit about templates and the ContentPresenter, you can build a simple template. The following code shows a basic template that adds an outline to a Label control. You should define the template in some object's Resources section. This example creates the template in the Window's Resources section so you can use it on any Label in that Window.
<ControlTemplate x:Key="temOutlinedLabel" TargetType="Label">
<Border BorderBrush="Red" BorderThickness="5">
The x:Key attribute gives the template a name so the code can refer to it later. The TargetType attribute controls which type(s) of controls can use the template.
The template contains a Border control that displays a thick red border. That control holds the ContentPresenter. Typically, the label control's content is simple text, so the ContentPresenter displays the text. However, if you set the Label's content to something unusual, such as a Button, the ContentPresenter happily drops that into the Border instead.
The following code shows how the OutlinedLabel example program (available in the downloadable sample code in both VB.NET and C#), shown in Figure 2, uses this template. The Template attribute tells the control to use the temOutlinedLabel template.
<Label Margin="10" Content="Outline Me!"