Static Resources in Silverlight class library

Generally in Silverlight application we put styles in "App.xaml", as any style declared here will be available in any control added in the application. But what is the option in case of Silverlight class library as there is no App.xmal? To create style in Silverlight class library, Silverlight provides Resource Dictionary. Here are the steps to add Resource Dictionary.

1. Create Silverlight Application project


Your project will be loaded like this:


2. Add Silverlight Class Library project

Add Silverlight Class Library project in your solution. Once the Silverlight Class Library project is added, right click on the project, and add Silverlight Resource Dictionary from "Add New Item" dialog box.


3. Add style in Resource Dictionary

Add below code in Resource Dictionary file (in my solution Dictionary1.xaml).

<Style TargetType="TextBlock" x:Key="TextBlockStyle">
       <Setter Property="Foreground" Value="Blue" />
       <Setter Property="FontSize" Value="20" />
       <Setter Property="FontWeight" Value="Bold" />

The above style code will be applied to TextBlock control, it will make text color to blue, font size to 20 and font weight to bold. You may add some more setter property as per you application requirement.

4. Apply styles in UserControl

Add new Silverlight UserControl on the Class Library project and add below code in user control.

             <ResourceDictionary Source="Dictionary1.xaml"/>
<Grid Background="White" Margin="20,20,20,20">
       <TextBlock Text="This is Static Resource test." Style="{StaticResource TextBlockStyle}"  />

The most important point you should see is Style="{StaticResource TextBlockStyle}"You have to specifically provide the style name in control style property.

5. Run Application

To see the style change, you may add StackPanel in MainPage.xaml and add UserControl as children of StackPanel in page Loaded event.

void MainPage_Loaded(object sender, RoutedEventArgs e)
    SilverlightControl1 control = new SilverlightControl1();

Now when you run the application you will see result as in below image.

In this article you have seen how to create and use Static Resource in Silverlight.