Content controls

While this control is not often used directly, one use for it is to render a single data item according to a particular template. In fact, we often use a ContentControl to display our View Models and use a DataTemplate object that renders the associated View. Alternatively, we might use some form of ItemsControl to display a group of items and a ContentControl to display the selected item.

As we found out earlier, when looking at the inheritance hierarchy of the Button control, the ContentControl class extends the Control class and adds the ability for derived classes to contain any single CLR object. Note that if we need to specify more than a single object of content, we can use a single panel object that contains further objects:

<Button Width="80" Height="30" TextElement.FontSize="14"> 
  <StackPanel Orientation="Horizontal"> 
    <Rectangle Fill="Cyan" Stroke="Black" StrokeThickness="1" Width="16" 
      Height="16" /> 
    <TextBlock Text="Cyan" Margin="5,0,0,0" /> 
  </StackPanel> 
</Button>

We can specify this content through the use of the Content property. However, the ContentControl class specifies the Content property in a ContentPropertyAttribute attribute in its class definition and this enables us to set the content by simply declaring the child element directly within the control in the XAML. This attribute is used by the XAML processor when it processes XAML child elements.

If the content is of type string, then we can use the ContentStringFormat property to specify a particular format for it. Otherwise, we can use the ContentTemplate property to specify a DataTemplate to use while rendering the content. Alternatively, the ContentTemplateSelector property is of type DataTemplateSelector and also enables us to select a DataTemplate, but based upon some custom condition that we may have. All derived classes have access to these properties in order to shape the output of their content.

However, this control is also able to display many primitive types without us having to specify a custom template. Let's move on to the next section now, where we'll find out exactly how it manages to accomplish this.