post icon

Silverlight Tip of the Day #1 – Using Static Resources in Class Libraries

A common place to put styles in Silverlight applications is the App.xaml file. Any style declared in App.xaml is automatically picked up by any of your custom controls in your application. However, if you create a Silverlight Class Library you will notice there is no App.xaml file to put styles in.

In order to create styles in a Silverlight Class Library there are primarily two steps you can take in order for your controls to pick up on the statically declared styles.

Step #1. Add a Silverlight Resource Dictionary

Using Visual Studio, from your class library project in the solution explorer, right click and choose “Add New Item”. From there, choose “Silverlight Resource Dictionary” as seen in the screenshot below giving it any name you want.

image

Step #2: In your controls, add a reference to the resource you just added.

<UserControl.Resources> 
    <ResourceDictionary> 
        <ResourceDictionary.MergedDictionaries> 
            <ResourceDictionary Source="StyleDictionary.xaml"/> 
        </ResourceDictionary.MergedDictionaries> 
    </ResourceDictionary> 
</UserControl.Resources>

At this point, you can now reference any style you have declared in this resource dictionary from your controls.

Example:

<Button Style="{StaticResource GlossyButton}" Content="Hi" Grid.Row="3"/>

Download source: Tip of the Day #1 Source

Thank you,

–Mike

3 Comments

Leave a comment
  1. Raj
    26. Apr, 2010 at 8:44 am #

    Hi Mike,

    Is this is Same as generic.xaml or Different.

  2. admin
    26. Apr, 2010 at 9:19 am #

    I tried putting the style in generic.xaml but my XAML will not pick up on styles declared in the file. The only way I could get them to be recognized is if I added the resouce dictionary as described in this blog.

    If anyone knows of any tricks to get things working in generic.xaml please let me know.

Trackbacks/Pingbacks

  1. Dew Drop – April 22, 2010 | Alvin Ashcraft's Morning Dew - 22. Apr, 2010

    [...] Silverlight Tip of the Day #1 – Using Static Resources in Class Libraries (Mike Snow) [...]