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

1.gif

Your project will be loaded like this:

2.gif

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.gif

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" />
</Style>

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.

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

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();
    MainPanel.Children.Add(control);
}

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

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


Similar Articles