Monday, April 14, 2008

Merging a ResourceDictionary at runtime - In Silverlight 2 Beta 1

I've struggled for quite a few hours now to get my silverlight 2 Beta 1 application to get Styling and Theming information from a ResourceDictinary file loaded at runtime.

Haa Haa I say, finally figured it out. (See source code below).

One important thing to note: You HAVE to key the items in the dictionary with x:Name. There is no Dependency Property for x:Key.

However, if will work until MS hopefully implements the Source property like on the WPF ResourceDictionary class.

This is how I use the helper class:

Usage:

private void Application_Startup(object sender, StartupEventArgs e)
{
DictionaryHelper.MergeDictionary(Application.Current.Resources,
new Uri("default/theme.xaml", UriKind.Relative));

// Load the main control
this.RootVisual = new Page();
}


Helper Class Source:

using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Resources;
using System.IO;
using System.Windows.Markup;

namespace PuzzleApp
{
public static class DictionaryHelper
{
public static void MergeDictionary(ResourceDictionary destination, Uri source)
{
StreamResourceInfo streamInfo = Application.GetResourceStream(source);
using (StreamReader reader = new StreamReader(streamInfo.Stream))
{
ResourceDictionary sourceDic = (ResourceDictionary)XamlReader.Load(reader.ReadToEnd());

foreach (DependencyObject item in sourceDic.ToArray())
{
sourceDic.Remove(item);

destination.Add(item);
}
}
}
}
}