Putting resource in separate xaml files

In Silverlight, we usually define several shared resources (i.e. definition of Color, Brush, Style, etc) in an individual xaml file (i.e. inside <UserControl.Resources></UserControl.Resources>, which scope is local to that file only) or in the App.xaml file (i.e. inside <Application.Resources></Application.Resources>, which scope is global to the app). The latter approach is good way to share resources but it can easily make the App.xaml file becomes huge. Another approach is to put the resources in one or more xaml files, which can be loaded at runtime.

For example, our app has a button control on the page, the xaml code looks something like:

<

Button x:Name="MyButton" Content="My Sample Button" />

We want to assign one of the button properties with resource we load externally. Following are steps to create the separate xaml resource file and use the resources in the app:

  1. Create an empty xaml file (i.e. let's name it MyResources.xaml) and add it to the Silverlight project
  2. Change the Build Action property of the file from "None" or "Page" to "Content"
  3. Put the resource dictionary definition in the xaml file, for example:

<ResourceDictionary

   xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"

   xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml">

    <SolidColorBrush x:Name="RedColorBrush"

                    Color="Red"

                     />

</ResourceDictionary>

Then add following code to load the resource dictionary and use the brush object on the existing button:

            // Read resources.xaml included in the project

            string xaml = null;

            StreamResourceInfo sri = Application.GetResourceStream(new Uri("MyResources.xaml", UriKind.Relative));

            using (StreamReader reader = new StreamReader(sri.Stream))

            {

                xaml = reader.ReadToEnd();

            }

            // Load the resource dictionary and access the resource using key

            if (xaml != null)

            {

                _globalResources = (ResourceDictionary)XamlReader.Load(xaml);

                // Now we can use the resource defined in the dictionary

                SolidColorBrush redColorBrush = (SolidColorBrush) _globalResources ["RedColorBrush"];

                MyButton.Background = redColorBrush;

            }