Control Templates in Silverlight

Silverlight enables to customize controls in several ways. We can customize a control by modifying the default template. So it will modify the visual appearance of an existing control or a new one.

Control templates are used to specify the visual structure (the appearance) and visual behavior of a control and keep his logic. When you create and use a control template, you replace the appearance of the existing control without changing its functionality. This is possible because there is a defined contract for the control which maintains separate the visual and the logic. The control consists of:

  • Visual properties are exposed on the control. These properties could be used in the template with the Template Binding.

  • Control Parts which is expected to maintain the visual structure of the control.

  • Logic is associated with the part in the template.

For more details about contract considerations, check herearrow-up-right.

The control customization using control templates allows you to:

  • Change the visual structure of a control

  • Change the appearance of a control to its state

  • Specify the behavior between the state's transition of a control

Customizing a Control

This section describes the most common ways to customize a control by using Control Templates.

Locally inline definition

The Control Template can be defined by using the control.template property

<Button IsHitTestVisible="True" IsTabStop="False" Grid.Column="1" Grid.Row="0" Grid.RowSpan="2" >
    <Button.Template>
        <ControlTemplate TargetType="Button">
            <Grid Background="Transparent"/>
        </ControlTemplate>
    </Button.Template>
</Button>

Control template defined in resources

The Control Template can be defined by a resource reference directly as a template.

And the use of the previously defined template will be:

Control Template definition in resource style

The Control Template can be defined as part of a style in any kind of resource.

Silverlight templated control

Silverlight allows you to define your own with a custom style, or extend from another. This will generate a style for the control in the Themes/Generic.xaml, and generate a class for the created control.

Last updated

Was this helpful?