#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">
                <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}"/>


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}">
                    <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"/>


Get every new post delivered to your Inbox.

Join 416 other followers