#176 – Two Kinds of Templates

In WPF, there are two different kinds of templatescontrol templates and data templates.

Control templates allow you to exactly specify the visual tree of a control, i.e. its constituent controls.  The example below shows a Button control being constructed out of a Button and two Label controls.

        <Button Name="btnWithTemplate" Content="Recreate Me" Foreground="Blue">
            <Button.Template>
                <ControlTemplate TargetType="{x:Type Button}">
                    <StackPanel Orientation="Horizontal">
                        <Label Content="**" Foreground="{TemplateBinding Foreground}"/>
                        <Button Content="{TemplateBinding Content}" Foreground="{TemplateBinding Foreground}"/>
                        <Label Content="**" Foreground="{TemplateBinding Foreground}"/>
                    </StackPanel>
                </ControlTemplate>
            </Button.Template>
        </Button>

 

Data templates allow you to specify how a bound data object will be mapped to one or more controls.  The example below maps properties of a Person object to several labels.

        <Label Name="lblPerson" Content="{Binding}">
            <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>

Advertisement

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

2 Responses to #176 – Two Kinds of Templates

  1. Pingback: Tweets that mention #176 – Two Kinds of Templates « 2,000 Things You Should Know About WPF -- Topsy.com

  2. Loreno says:

    It is a little confusing that Button has a Template, while label has a ContentTemplate.

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: