#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}">
            <Label.Template>
                <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}"/>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsEnabled" Value="false">
                            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Label.Template>
            <Label.ContentTemplate>
                <DataTemplate>
                    <Border BorderThickness="2" BorderBrush="DarkBlue">
                        <StackPanel Orientation="Vertical">
                            <StackPanel Orientation="Horizontal">
                                <Label Content="{Binding Path=FirstName}"/>
                                <Label Content="{Binding Path=LastName}" FontWeight="Bold"/>
                            </StackPanel>
                            <Label Content="{Binding Path=BirthYear}" FontStyle="Italic"/>
                        </StackPanel>
                    </Border>
                </DataTemplate>
            </Label.ContentTemplate>
        </Label>
Advertisements