#178 – A Control Can Have Both a Control Template and A Data Template

A control template dictates a control’s constituent controls, while a data template dictates how bound data will be rendered.  A control can actually have both types of templates at the same time.

In the XAML fragment below, we specify a Label‘s Template property, setting it to a ControlTemplate.  (This is actually the default control template for a Label).

We also specify the label’s ContentTemplate as a DataTemplate.  This template dictates how we’ll render the actual data (content) bound to the Label.

        <Label Name="lblPerson" Content="{Binding}">
                <ControlTemplate TargetType="{x:Type Label}">
                    <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="true">
                        <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                        <Trigger Property="IsEnabled" Value="false">
                            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
                    <Border BorderThickness="2" BorderBrush="DarkBlue">
                        <StackPanel Orientation="Vertical">
                            <StackPanel Orientation="Horizontal">
                                <Label Content="{Binding Path=FirstName}"/>
                                <Label Content="{Binding Path=LastName}" FontWeight="Bold"/>
                            <Label Content="{Binding Path=BirthYear}" FontStyle="Italic"/>

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #178 – A Control Can Have Both a Control Template and A Data Template

  1. Pingback: #1,071 – How TextBox Reacts to Gaining Keyboard Focus | 2,000 Things You Should Know About WPF

  2. Loreno says:

    It would be good to mention that Label’s ContentTemplate is what will be actually displayed inside of ContentPresenter.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: