Click to Rate and Give Feedback
MSDN
MSDN Library
Web Development
Silverlight
Visual Design
Controls
 Customizing the Appearance of an Ex...
Silverlight
Customizing the Appearance of an Existing Control by Creating a ControlTemplate

Updated: November 2008

A ControlTemplate specifies the visual structure and visual behavior of a control. You can customize the appearance of a control by giving it a new ControlTemplate. When you create a ControlTemplate, you replace the appearance of an existing control without changing its functionality. For example, you can make the buttons in your application round rather than the default square shape, but the button will still raise the Click event.

This topic explains the various parts of a ControlTemplate, demonstrates creating a simple ControlTemplate for a Button, and explains how to understand the control contract of a control so you can customize its appearance. Because you create a ControlTemplate in XAML, you can change a control's appearance without writing any code. The examples in this topic show the XAML that is used to customize the appearance of a Button. For the complete example discussed in this topic, see How to: Create a Custom Appearance for a Button. You can also use a designer such as Microsoft Expression Blend 2 Service Pack 1 to accomplish the same thing. For more information about using Expression Blend 2 SP1, see Create a Reusable Template for a System Control.

Click the following link to see the ControlTemplate example that is used in this topic.

Run the sample.

This topic contains the following sections.

This topic assumes that you understand creating and using controls and styles as discussed in Getting Started with Controls. The concepts discussed in this topic apply to elements that inherit from the Control class, except for the UserControl. You cannot apply a ControlTemplate to a UserControl.

Controls have many properties, such as Background, Foreground, and FontFamily, that you can set to specify different aspects of the control's appearance, but the changes that you can make by setting these properties are limited. For example, you can set the Foreground property to blue and FontStyle to italic on a CheckBox.

Without the ability to create a new ControlTemplate for controls, all controls in every Silverlight-based application would have the same general appearance, which would limit the ability to create an application with a custom look and feel. By default, every CheckBox has similar characteristics. For example, the content of the CheckBox is always to the right of the selection indicator, and the check mark is always used to indicate that the CheckBox is selected.

You create a ControlTemplate when you want to customize the control's appearance beyond what setting the other properties on the control will do. In the example of the CheckBox, suppose that you want the content of the check box to be above the selection indicator and an X to indicate that the CheckBox is selected. You specify this is the ControlTemplate of the CheckBox.

Click the following link to see a CheckBox that uses a default ControlTemplate and CheckBox that uses a custom ControlTemplate to place the content of the CheckBox above the selection indicator and display an X when the CheckBox is selected.

Run this sample.

The ControlTemplate for the CheckBox in this sample is relatively complex, so this topic uses a simpler example of creating a ControlTemplate for a Button.

The Template property specifies the ControlTemplate of a control. Like many properties, the Template property can be set in the following ways:

The following example demonstrates setting the Template property locally and defining the ControlTemplate inline.

<Button Content="Button1">
  <Button.Template>
    <ControlTemplate TargetType="Button">

      <!--Define the ControlTemplate here.-->

    </ControlTemplate>
  </Button.Template>
</Button> 

The following example demonstrates defining the ControlTemplate as a resource and setting the Template to a reference to the resource.

<StackPanel>
  <StackPanel.Resources>
    <ControlTemplate x:Key="ButtonTemplate" TargetType="Button">

      <!--Define the ControlTemplate here.-->

    </ControlTemplate>
  </StackPanel.Resources>

  <Button Template="{StaticResource ButtonTemplate}" Content="Button1"/>
</StackPanel>

The following example demonstrates setting the Template property and defining the ControlTemplate in a Style.

<StackPanel>
  <StackPanel.Resources>
    <Style x:Key="ButtonStyle" TargetType="Button"> 
      <Setter Property="Template">
        <Setter.Value>
          <ControlTemplate TargetType="Button">

            <!--Define the ControlTemplate here.-->

          </ControlTemplate>
        </Setter.Value>
      </Setter>
    </Style>
  </StackPanel.Resources>
  <Button Style="{StaticResource ButtonStyle}" Content="Button1"/>
</StackPanel>

Although all three of these methods are valid ways to define a ControlTemplate, it is probably most common to see the Template property set in a Style. When you see a ControlTemplate is set in a Style, realize that the style just sets the Template property, just as it does for any other property.

In Silverlight, a control is often a composite FrameworkElement objects. When you create a ControlTemplate, you combine FrameworkElement objects to build a single control. A ControlTemplate must have only one FrameworkElement as its root element. The root element usually contains other FrameworkElement objects. The combination of objects is makes up the control's visual structure.

The following example creates a custom ControlTemplate for the Button. The ControlTemplate creates the visual structure of the Button. This example does not change the button's appearance when you point to it or click it. Changing the button's appearance when it is in a different state is discussed later in this topic.

In this example, the visual structure is made up of the following parts:

<ControlTemplate TargetType="Button">
  <Border x:Name="RootElement">

    <!--Create the SolidColorBrush for the Background 
        as an object elemment and give it a name so 
        it can be referred to elsewhere in the control template.-->
    <Border.Background>
      <SolidColorBrush x:Name="BorderBrush" Color="Black"/>
    </Border.Background>

    <!--Create a border that has a different color by adding smaller grid.
        The background of this grid is specificied by the button's Background
        property.-->
    <Grid Margin="4" Background="{TemplateBinding Background}">

      <!--Use a ContentPresenter to display the Content of
          the Button.-->
      <ContentPresenter
          HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
          VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
          Margin="4,5,4,4" />
    </Grid>

  </Border>
</ControlTemplate>

Preserving the Functionality of a Control's Properties by Using TemplateBinding

When you create a new ControlTemplate, you still might want to use the public properties to change the control's appearance. The TemplateBinding markup extension binds a property of an element that is in the ControlTemplate to a public property that is defined by the control. The preceding example uses the TemplateBinding markup extension to bind properties of elements that are in the ControlTemplate to public properties that are defined by the button. For example, the Border has its Background property set to {TemplateBinding Background}. Because Background is template bound, you can create multiple buttons that use the same ControlTemplate and set the Background to different values on each button. If Background was not template bound in the ControlTemplate, setting the Background of a button would have no impact on the button's appearance.

In the case of a few properties, it is not necessary to use TemplateBinding because the FrameworkElement objects in the ControlTemplate automatically inherit values from a parent FrameworkElement. The following properties are automatically inherited:

Also, if the ContentPresenter is in the ControlTemplate of a ContentControl, the ContentPresenter will automatically bind to the ContentTemplate and Content properties. Likewise, an ItemsPresenter that is in the ControlTemplate of an ItemsControl will automatically bind to the Items and ItemsPresenter properties.

The following example creates two buttons that use the ControlTemplate defined in the preceding example. The example sets the Background, Foreground, and FontSize properties on each button. Setting the Background property has an effect because it is template bound in the ControlTemplate. Even though the Foreground and FontSize properties are not template bound, setting them has an effect because their values are inherited.

<StackPanel>
  <Button Style="{StaticResource newTemplate}" 
          Background="Navy" Foreground="White" FontSize="14"
          Content="Button1"/>

  <Button Style="{StaticResource newTemplate}" 
          Background="Purple" Foreground="White" FontSize="14"
          Content="Button2" Click="Button_Click"/>
</StackPanel>

Run this sample.

The difference between a button with its default appearance and the button in the preceding example is that the default button subtly changes when it is in different states. For example, the default button's appearance changes when the button is pressed, or when the mouse pointer is over the button. Although the ControlTemplate does not change the functionality of a control, it does change the control's visual behavior. A visual behavior describes the control appearance when it is in a certain state. To understand the difference between the functionality and visual behavior of a control, consider the button example. The button's functionality is to raise the Click event when it is clicked, but the button's visual behavior is to change its appearance when it is pointed to or pressed.

You use VisualState objects to specify the appearance of a control when it is in a certain state. A VisualState contains a Storyboard that changes the appearance of the elements that are in the ControlTemplate. You do not have to write any code to make this occur because the control's logic changes state by using the VisualStateManager. When the control enters the state that is specified by the VisualState..::.Name property, the storyboard begins. When the control exits the state, the Storyboard stops.

The following example shows the VisualState that changes the appearance of a Button when the mouse pointer is over it. The Name of the VisualState matches the name specified by the TemplateVisualStateAttribute on the Button class. The Storyboard changes the button's border color by changing the color of the BorderBrush. If you refer to the ControlTemplate example at the beginning of this topic, you will recall that BorderBrush is the name of the SolidColorBrush that is assigned to the Background of the Border.

<!--Change the border of the button to red when the
    mouse is over the button.-->
<vsm:VisualState x:Name="MouseOver">
  <Storyboard>
    <ColorAnimation Storyboard.TargetName="BorderBrush" 
                    Storyboard.TargetProperty="Color" To="Red" />

  </Storyboard>
</vsm:VisualState>

The control is responsible for defining the states as part of its control contract, which is discussed in detail in Customizing Other Controls by Understanding the Control Contract later in this topic. The states of a control are specified by the TemplateVisualStateAttribute, which is placed on the control's class definition. A TemplateVisualStateAttribute specifies the name of the state and the name of the state group that the state belongs to. The following example shows the states that are specified for the Button.

C#
[TemplateVisualState(Name = "Normal", GroupName = "CommonStates")]
[TemplateVisualState(Name = "MouseOver", GroupName = "CommonStates")]
[TemplateVisualState(Name = "Pressed", GroupName = "CommonStates")]
[TemplateVisualState(Name = "Disabled", GroupName = "CommonStates")]
[TemplateVisualState(Name = "Unfocused", GroupName = "FocusStates")]
[TemplateVisualState(Name = "Focused", GroupName = "FocusStates")]
public class Button : ButtonBase
{
}

Visual Basic
<TemplateVisualStateAttribute(Name:="Pressed", GroupName:="CommonStates")> _
<TemplateVisualStateAttribute(Name:="Focused", GroupName:="FocusStates")> _
<TemplateVisualStateAttribute(Name:="Normal", GroupName:="CommonStates")> _
<TemplateVisualStateAttribute(Name:="MouseOver", GroupName:="CommonStates")> _
<TemplateVisualStateAttribute(Name:="Disabled", GroupName:="CommonStates")> _
<TemplateVisualStateAttribute(Name:="Unfocused", GroupName:="FocusStates")> _
Public Class Button
    Inherits ButtonBase

End Class

The TemplateVisualStateAttribute..::.GroupName property specifies which group a state belongs to. In the preceding example, the Button defines two state groups: the CommonStates group contains the Normal, MouseOver, Pressed, and Disabled states. The FocusStates group contains the Focused and Unfocused states. States in the same state group are mutually exclusive. The control is always in exactly one state per group. For example, a Button can have focus even when the mouse pointer is not over it, so a Button in the Focused state can be in the MouseOver, Pressed, or Normal state.

You add VisualState objects to VisualStateGroup objects. You add VisualStateGroup objects to the VisualStateManager.VisualStateGroups attached property, which you set on the root FrameworkElement of the ControlTemplate. The following example defines the VisualState objects for the Normal, MouseOver, and Pressed states, which are all in the CommonStates group. The Disabled state and the states in the FocusStates group are omitted to keep the example short, but they are included in the entire example in How to: Create a Custom Appearance for a Button.

<ControlTemplate TargetType="Button" 
                 xmlns:vsm="clr-namespace:System.Windows;assembly=System.Windows">
  <Border x:Name="RootElement">

    <vsm:VisualStateManager.VisualStateGroups>

      <!--Define the states and transitions for the common states.
          The states in the VisualStateGroup are mutually exclusive to
          each other.-->
      <vsm:VisualStateGroup x:Name="CommonStates">

        <!--The Normal state is the state the button is in
            when it is not in another state from this VisualStateGroup.-->
        <vsm:VisualState x:Name="Normal" />

        <!--Change the SolidColorBrush, BorderBrush, to red when the
            mouse is over the button.-->
        <vsm:VisualState x:Name="MouseOver">
          <Storyboard>
            <ColorAnimation Storyboard.TargetName="BorderBrush" 
                              Storyboard.TargetProperty="Color" To="Red" />

          </Storyboard>
        </vsm:VisualState>

        <!--Change the SolidColorBrush, BorderBrush, to Transparent when the
            button is pressed.-->
        <vsm:VisualState x:Name="Pressed">
          <Storyboard >
            <ColorAnimation Storyboard.TargetName="BorderBrush" 
                              Storyboard.TargetProperty="Color" To="Transparent"/>
          </Storyboard>
        </vsm:VisualState>

        <!--The Disabled state is omitted for brevity.-->
      </vsm:VisualStateGroup>
    </vsm:VisualStateManager.VisualStateGroups>

    <Border.Background>
      <SolidColorBrush x:Name="BorderBrush" Color="Black"/>
    </Border.Background>

    <Grid Background="{TemplateBinding Background}" Margin="4">
      <ContentPresenter
        HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
        VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
        Margin="4,5,4,4" />

    </Grid>


  </Border>
</ControlTemplate>

Run this sample.

If you run the preceding sample, you will notice that the appearance of a button changes when you point to it. The appearance of the button also changes when you click it, but unless you keep the button pressed for a full second, you do not see the effect. By default, an animation takes one second to occur. Because users are likely to click and release a button in much less time, the visual feedback will not be effective if you leave the ControlTemplate in its default state.

You can specify the amount of time that it takes an animation to occur to smoothly transition a control from one state to another by adding VisualTransition objects to the ControlTemplate. When you create a VisualTransition, you specify one or more of the following:

  • The time it takes for a transition between states to occur.

  • Additional changes in the control's appearance that occur at the time of the transition.

  • Which states the VisualTransition is applied to.

Specifying the Duration of a Transition

You can specify how long a transition takes by setting the GeneratedDuration property. The preceding example has a VisualState that specifies that the button's border becomes transparent when the button is pressed, but the animation takes too long to be noticeable if the button is quickly pressed and released. You can use a VisualTransition to specify the amount of time it takes the control to transition into the pressed state. The following example specifies that the control takes one hundredth of a second to go into the pressed state.

<!--Take one hundredth of a second to transition to the
    Pressed state.-->
<vsm:VisualTransition To="Pressed" 
                      GeneratedDuration="0:0:0.01" />

Specifying Changes to the Control's Appearance During a Transition

The VisualTransition contains a Storyboard that begins when the control transitions between states. For example, you can specify that a certain animation occurs when the control transitions from the MouseOver state to the Normal State. The following example creates a VisualTransition that specifies that when the user moves the mouse pointer away from the button, the button's border changes to blue, then to yellow, then to black in 1.5 seconds.

<!--Take one and a half seconds to transition from the
    MouseOver state to the Normal state. 
    Have the SolidColorBrush, BorderBrush, fade to blue, 
    then to yellow, and then to black in that time.-->
<vsm:VisualTransition From="MouseOver" To="Normal" 
                      GeneratedDuration="0:0:1.5">
  <Storyboard>
    <ColorAnimationUsingKeyFrames
      Storyboard.TargetProperty="Color"
      Storyboard.TargetName="BorderBrush"
      FillBehavior="HoldEnd" >

      <ColorAnimationUsingKeyFrames.KeyFrames>

        <LinearColorKeyFrame Value="Blue" 
                             KeyTime="0:0:0.5" />
        <LinearColorKeyFrame Value="Yellow" 
                             KeyTime="0:0:1" />
        <LinearColorKeyFrame Value="Black" 
                             KeyTime="0:0:1.5" />

      </ColorAnimationUsingKeyFrames.KeyFrames>
    </ColorAnimationUsingKeyFrames>
  </Storyboard>
</vsm:VisualTransition>

Specifying When a VisualTransition Is Applied

In the preceding example, the VisualTransition is applied when the control goes from the MouseOver state to the Normal state; in the example before that, the VisualTransition is applied when the control goes into the Pressed state. A VisualTransition can be restricted to apply to only certain states, or it can be applied any time the control transitions between states. You restrict when a VisualTransition is applied by setting the To and From properties. The following table describes the levels of restriction from most restrictive to least restrictive.

Type of restriction

Value of From

Value of To

From a specified state to another specified state

The name of a VisualState

The name of a VisualState

From any state to a specified state

Not set

The name of a VisualState

From a specified state to any state

The name of a VisualState

Not set

From any state to any other state

Not set

Not set

You can have multiple VisualTransition objects in a VisualStateGroup that refer to the same state, but they will be used in the order that the table above specifies. In the following example, there are two VisualTransition objects. When the control transitions from the Pressed state to the MouseOver state, the VisualTransition that has both From and To set is used. When the control transitions from a state that is not Pressed to the MouseOver state, the other state is used.

<!--Take one half second to trasition to the MouseOver state.-->
<vsm:VisualTransition To="MouseOver" 
                      GeneratedDuration="0:0:0.5" />

<!--Take one hundredth of a second to transition from the
    Pressed state to the MouseOver state.-->
<vsm:VisualTransition From="Pressed" To="MouseOver" 
                      GeneratedDuration="0:0:0.01" />

The VisualStateGroup has a Transitions property that contains the