Wednesday, October 29, 2008

Implicit Styles in Silverlight

WPF supports both explicit and implicit styles (application wide styles), while Silverlight supports only explicit styles. This means that in Silverlight when you define a style as a resource, you have to give it an explicit key, and call that key wherever you want the style to be applied. For example, if you have defined a TextBlock style in App.Resources, you have to explicity set the Style property on all TextBlocks within the application like this:

<TextBlock Text="Text1" Style="{StaticResource key1}"/>

<TextBlock Text="Text2" Style="{StaticResource key1}"/>

<TextBlock Text="Text3" Style="{StaticResource key1}"/>



This has been an issue Silverlight developers have been grappling with for a long time. The Silverlight 2 release (RTW) did not have a solution for this. Fortunately, the Silverlight Toolkit that has been released yesterday, comes with an ImplicitStyleManager that makes implicit styles possible in Silverlight. If you are not familiar with the Silverlight Toolkit, you can read about it here.

So, how do you make use of this?

1) Download the Silverlight Toolkit.

2) Copy Microsoft.Windows.Controls.Theming.dll that comes within the toolkit to your Silverlight project and add a reference to it.

3) Add a reference to the namespace within which the ImplicitStyleManager resides:

xmlns:theming="clr-namespace:Microsoft.Windows.Controls.Theming; assembly=Microsoft.Windows.Controls.Theming"


4) Now use the ApplyMode property to set implicit styling:

<StackPanel x:Name="stackPanel" theming:ImplicitStyleManager.ApplyMode="OneTime">

<TextBlock Text="Static Text 1" />

<TextBlock Text="Static Text 2" />

<StackPanel>


5) Of course, you should have defined the style somewhere in the resources collection as shown below:

<Application.Resources>

<Style TargetType="TextBlock">

<Setter Property="Foreground" Value="Red" />

<Setter Property="FontSize" Value="20" />

<Setter Property="Margin" Value="5" />

<Style>

<Application.Resources>


Now you are good to go. The ImplicitStyleManager will ensure that the style is passed down to the TextBlock down the element tree.

If you dynamically add a TextBlock to the element tree (at run time), you will find that the TextBlock will not get the style. In this case, you will have to set ImplicitStyleManager.ApplyMode="Auto". But setting it to Auto can have a major performance impact, so use this sparingly.

There you go - implicit styles in Silverlight :).