Tuesday, January 11, 2011

Typed styles in WPF

Based on my previous post, WPF Quiz #2, I would like to shed some light on a very important mechanism in WPF related to styles.
WPF has a very handy feature called typed-style, which is a style located in a resource dictionary, has no explicit key (or the key explicitly set as the type of the target) and is type specific. For an instance:

<Style TargetType="{x:Type Button}">
   <Setter Property="Background" Value="Red" />
</Style>

Having such a style in the Application's resource dictionary, every element of type Button will be automatically applied with this style unless explicitly set with a different style.

This is a very important mechanism in WPF which provides an intuitive and automatic option to create themes for the whole application just by creating a style for each relevant element and place them in the Application's resource dictionary (Silverlight programmers, you should wait for the next version… ;-)).
Using this neat feature, you should be aware of some facts.

1. Type specific style is not automatically applied on derived typed. For example, having a typed style for Window, Button or ListBox types, it won't be automatically applied on MyWindow, MyButton and MyListBox, but it could be explicitly set on them.

<Application x:Class="Quiz2.App"
           xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
           xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
           xmlns:local="clr-namespace:Quiz2"
           StartupUri="MainWindow.xaml">
 
   <Application.Resources>
       <Style TargetType="{x:Type Button}">
           <Setter Property="Background" Value="Red" />
       </Style>
     
       <Style TargetType="{x:Type local:MainWindow}">

Read more: Essential WPF and Young Brothers