Wednesday, March 25, 2009

Silverlight 3 Beta Merged Resource Dictionaries

This helps us to link resource dictionaries.That means we can split up our resource dictionaries into small files and link them together to act like a single resource dictionary.

Earlier when we develop a Silverlight custom control library we have to keep all the control styles and templates in a single resource dictionary file called generic.xaml.That is very much confusing and makes the generic.xaml very huge and complex.We can’t maintain that resource dictionary easily.The main advantage of Merged resource dictionary comes here.We can split up the styles and templates of each individual Silverlight control into separate resource dictionary files and maintain easily.

Also when we are in styling or templating controls in a complex user control we can split up similar styles into different resource dictionaries.Normally its very useful to separate Brushes and colors from the styles.

Creating Resource Dictionary

If you are using Visual studio there is no direct support to add a ResourceDictionary.So add a new UserControl and do the following.

  1. Delete the xaml.cs file
  2. Remove the x:Class attribute from UserControl’s xaml declaration.
  3. Remove the Width and Height properties
  4. Remove the default Grid control.
  5. Change Build action to Resource.
  6. Rename the UserControl XAML tag to ResourceDictionary.

Now the XAMl will look as follows

xmlns:x="" >

To create a new ResourceDictionary using Blend 3 ,go to resources tab.Click on the ‘+’ located at top right to show the creation dialog.Give the name and press ‘OK’.I will be writing another post in detail which describes creation and manipulation of ResourceDictionaries using blend.

Adding resources

Adding xaml elements into ResourceDictionary is same as before.We can add any xaml element including Button,Grid,Brush,Color,Templates,Styles etc…A typical Colors.xaml resource dictionary is shown below

xmlns:x="" >
<Color x:Key="bgcolor">Red</Color>

Merging resource dictionaries

ResourceDictionary now got a new property called MergedDictionaries.This is a collection of ResourceDictionaries.We can add any number of ResourceDictionaries into this.Also we can merge a ResourceDictionary into another ResourceDictionary.Below is a Brushes.xaml which uses the Colors.xaml as a merged resource dictionary.

<ResourceDictionary xmlns=""
<ResourceDictionary Source="Colors.xaml" />
<SolidColorBrush x:Key="background" Color="{StaticResource bgcolor}"/>

Now we got brushes.xaml.This can be merged again with UserControl.xaml in order to use the brushes.

<UserControl x:Class="CustomEffects.MainPage"
Width="400" Height="300">
<ResourceDictionary Source="Brushes.xaml" />
<Grid x:Name="LayoutRoot">
<Button Grid.Row="1"
Background="{StaticResource background}"
Content="Click to change"></Button>

Sample can be downloaded from here.

No comments: