Tuesday, March 08, 2011

Implicit Styling - Silverlight 4

Styling in Silverlight is similar to styling in HTML with CSS. It helps you keep your markup (HTML, XAML) code clean by putting all the properties into a separate file. At runtime, both the markup and the styles defined in the external style sheet are merged and give the look to the application as it was intended.

Styling was already available in Silverlight. However, up until Silverlight 4, not all of the functions had been implemented (as compared to WPF). The most striking one was the default or implicit styling. Assume you are creating a Silverlight application and all controls of a specific type, for example all Buttons throughout the application should have a particular font size, font weight etc. In previous versions of Silverlight, we had to create a style and apply this style on every instance of the Button. There was no way to tell Silverlight that a particular style was supposed to be the style that had to be applied on all controls of a certain type.

Implicit styling allows us to do exactly that. We can now define a style that does not have a Key (x:Key, remember?) set in its declaration (and thus only has a TargetType defined). At that point, we are saying to Silverlight: use this style for every instance of the type specified in the TargetType which does not have a style set.

The following piece of XAML code actually creates a default style for the TextBlock type and a named style called SectionHeaderStyle.

<Style TargetType="TextBlock">            
 <Setter Property="FontSize" Value="14"></Setter>            
 <Setter Property="FontWeight" Value="Normal"></Setter>            
 <Setter Property="FontFamily" Value="Verdana"></Setter>     
        <Setter Property="FontStyle" Value="Normal"></Setter>   
</Style>        
<Style x:Key="Header" TargetType="TextBlock">     
        <Setter Property="FontSize" Value="20"></Setter>         
 <Setter Property="FontWeight" Value="Bold"></Setter>     
 <Setter Property="FontFamily" Value="Verdana"></Setter>       
 <Setter Property="FontStyle" Value="Italic"></Setter>   
</Style>

Read more: Silver digita