Every WPF control has two attributes behavior and appearance. Behavior is defined by event and properties while appearance is defined by control template.
Controls have default templates applied to them.Templates define the complete hierarchy of controls or visual tree of the control.It is responsible for the complete appearance ,look and feel of the control.
In WPF control behavior is completely separate from its appearance.This allows developers to completely define the appearance of controls from scratch.
To modify the appearance of a control we can use styles.Styles are useful for setting properties of the controls.But sometimes we need to completely change the appearance of the control.We can use control templates to redefine the appearance of the controls.
Control template Example in WPF for a button
templates are defined in a similar way as styles.We can define a basic template as:
<ControlTemplate x:Key="Template Name" TargetType="{x:Type Control Name}"> <Grid> </Grid> </ControlTemplate>
To define the control template contents for button we will add the grid as:
<ControlTemplate x:Key="customButton" TargetType="{x:Type Button}"> <Grid > <Border Margin="2"/> <TextBox Height="40" Width="100"></TextBox> </Grid> </ControlTemplate>
As control templates are defined for specific controls ,we use the TargetType property of ControlTemplate when defining the template.We can use the grid panel or any other
layout panel which contains all the controls which makes up the control template.
We can apply the above control template to the button as :
<Button Template="{StaticResource customButton}" />
Leave a Reply