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:
<
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:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://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;