WPF: Styles and Templates


One of the great features that WPF introduced is that: it allows us to change a control's look and feel into almost anything.  Prior to WPF if we wanted to have an image or and image and text in a ComboBox, we need to look at a third party vendor to create it for us. And this can be done by using Styles and Template.

STYLE: When building your User Interface there is a need to give the elements a common look and you don't want to keep on having to define the same fonts, color schemes each time you add a label or textbox. So this is when it helps to define style resources which can then be readily picked up each time you define a new element on your form. In other words, Styles are used to set the properties of an object to particular values. WPF styles are like css in that they can be used to globally define the looks of certain elements, they can be paired to specific element by way of a key, or they can even be declared inline directly on an element. A Style allows Triggers based on styled object events, styled object property values, and data values. In turn, triggers allow the animation of the object's properties. Styles can change the appearance of your control but they will be dependent on the properties provided by the control itself.

This concept of setting properties is inherent in the syntax of styles:

<Canvas.Resources>
   <Style TargetType="{x:Type TextBlock}">
      <Setter Property="Canvas.Left" Value="30" />
      <Setter Property="Padding" Value="0" />
      <Setter Property="Height" Value="18" />
      <Setter Property="FontWeight" Value="Bold" />
   </Style>
   <Style TargetType="{x:Type TextBox}">
      <Setter Property="Canvas.Left" Value="130" />
      <Setter Property="Padding" Value="0" />
      <Setter Property="Height" Value="18" />
      <Setter Property="Width" Value="120" />
   </Style>
</Canvas.Resources>

TEMPLATE: Windows Presentation Foundation allows the developer to completely change the look and feel of the controls. This is accomplished by using Control Templates. ControlTemplate means the template for the Control we are changing. A Template is used to define the Visual Tree of a Control (ControlTemplate) or the Visual Tree of the representation of an object (DataTemplate). Templates in WPF allow you to fully change the UI of anything.

The concept of Control Template is shown below:

<Style x:Key="DialogButtonStyle" TargetType="Button">
   <Setter Property="Template">
      <Setter.Value>
      <ControlTemplate TargetType="{x:Type Button}">
   <Grid>
      <Ellipse Fill="{TemplateBinding Background}"
      Stroke="{TemplateBinding BorderBrush}"/>
      <ContentPresenter HorizontalAlignment="Center"
      VerticalAlignment="Center"/>
   </Grid>
      </ControlTemplate>
      </Setter.Value>
   </Setter>
</Style>

This style is defined as:
<Button Style="{StaticResource DialogButtonStyle}" />
Ebook Download
View all
Learn
View all
F11Research & Development, LLC