Style in WPF

In this article I will explain Style which is an important feature of the Windows Presentation Foundation

Introduction

Style in WPF is used to group a set of properties that can be applied to controls. It is similar to CSS that is used to style in HTML.

Let us see how we can style a control in WPF without using the Style feature

<StackPanel Orientation="Vertical">
     <Label Foreground="White" Background="Orange" Padding="5"BorderThickness="1"
          BorderBrush="Wheat" Height="30" Width="100" FontSize="15">
          Name
     </Label>
     <Label Foreground="White" Background="Orange" Padding="5" BorderThickness="1"
          BorderBrush="White" Height="30" Width="100" FontSize="15">
          City
     </Label>
     <Label Foreground="White" Background="Orange" Padding="5" BorderThickness="1"
          BorderBrush="White" Height="30" Width="100" FontSize="15">
          Address
     </Label>
</StackPanel>

 

Here we have used three labels with similar look and feel. This code will work but it’s not looking great and it’s not manageable if we have a large set of controls. Like if we want to change the background of labels we have to make changes to all the labels. Now look how we can simplify this using Style

<StackPanel Orientation="Vertical">
     <StackPanel.Resources>
          <Style x:Key="lblStyle" TargetType="Label">
               <Setter Property="Foreground" Value="White"/>
               <Setter Property="Background" Value="Orange"/>
               <Setter Property="Padding" Value="5"/>
               <Setter Property="BorderThickness" Value="1"/>
               <Setter Property="BorderBrush" Value="Wheat"/>
               <Setter Property="Height" Value="30"/>
               <Setter Property="Width" Value="100"/>
               <Setter Property="FontSize" Value="15"/>
          </Style>
     </StackPanel.Resources>
     <Label Style="{StaticResource lblStyle}">
          Name
     </Label>
     <Label Style="{StaticResource lblStyle}">
          City
     </Label>
     <Label Style="{StaticResource lblStyle}">
          Address
     </Label>
</StackPanel>

Here we have grouped properties of the labels under a Style and given referendce of this Style in all the labels where we wanted similar look. TargetType attribute is used here to indicate that Style can be used only in Label conrols. Now if we want to make change in a property, we only have to change it in the Style and it will be applied in all the labels using this Style.

A Style can also be inherited to create a new Style like if we want to add Margin property in the style following code can be added to create  a new Style based on previous one

<Style x:Key="lblStyleNew" TargetType="Label" BasedOn="{StaticResource lblStyle}">
     <Setter Property="Background" Value="Red"/>
</Style>
<Label Style="{StaticResource lblStyleNew}">
     Name
</Label>

Leave a Reply

Your email address will not be published. Required fields are marked *