#176 – Two Kinds of Templates
January 4, 2011 1 Comment
In WPF, there are two different kinds of templates–control 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>

