Monday 21 November 2011

Introduction to Styles in WPF

Introduction

Imagine you want to create an application with a unique design. All your buttons should have an orange background and an italic font. Doing this the conventional way means that you have to set the Background and the FontStyle property on every single button.
 
<StackPanel Orientation="Horizontal" VerticalAlignment="Top">
    <Button Background="Orange" FontStyle="Italic" 
            Padding="8,4" Margin="4">Styles</Button>
    <Button Background="Orange" FontStyle="Italic" 
            Padding="8,4" Margin="4">are</Button>
    <Button Background="Orange" FontStyle="Italic" 
            Padding="8,4" Margin="4">cool</Button>
</StackPanel>
 
 

This code is neither maintainable nor short and clear. The solution for this problem are styles.
The concept of styles let you remove all properties values from the individual user interface elements and combine them into a style. A style consists of a list of setters. If you apply this style to an element it sets all properties with the specified values. The idea is quite similar to Cascading Styles Sheets (CSS) that we know from web development.
To make the style accessible to your controls you need to add it to the resources. Any control in WPF have a list of resources that is inherited to all controls beneath the visual tree. That's the reason why we need to specify a x:Key="myStyle" property that defines a unique resource identifier.
To apply the style to a control we set the Style property to our style. To get it from the resources we use the {StaticResource [resourceKey]} markup extension.
 
<Window>
    <Window.Resources>
        <Style x:Key="myStyle" TargetType="Button">
           <Setter Property="Background" Value="Orange" />
           <Setter Property="FontStyle" Value="Italic" />
           <Setter Property="Padding" Value="8,4" />
           <Setter Property="Margin" Value="4" />
        </Style>
    </Window.Resources>
 
    <StackPanel Orientation="Horizontal" VerticalAlignment="Top">
        <Button Style="{StaticResource myStyle}">Styles</Button>
        <Button Style="{StaticResource myStyle}">are</Button>
        <Button Style="{StaticResource myStyle}">cool</Button>
    </StackPanel>
</Window>
 
 

What we have achieved now is
  • A maintainable code base
  • Removed the redundancy
  • Change the appearance of a set of controls from a single point
  • Possibility to swap the styles at runtime.

Style inheritance

A style in WPF can base on another style. This allows you to specify a base style that sets common properties and derive from it for specialized controls.
 
<Style x:Key="baseStyle">
  <Setter Property="FontSize" Value="12" />
  <Setter Property="Background" Value="Orange" />
</Style>
 
 
<Style x:Key="boldStyle" BasedOn="{StaticResource baseStyle}">
  <Setter Property="FontWeight" Value="Bold" />
</Style>
 
 

No comments:

Post a Comment