Silverlight 3 – Dynamically Loading and Merging Resource Dictionary

Posted by: Mahesh Sabnis , on 8/19/2009, in Category Silverlight 2, 3, 4 and 5
Views: 60118
Abstract: This article explains how to dynamically load and merge resource dictionaries declared inside the Silverlight 3 applications and inside the external Silverlight library.
Silverlight 3 – Dynamically Loading and Merging Resource Dictionary
 
This article explains how to dynamically load and merge resource dictionaries declared inside the Silverlight 3 applications and inside the external Silverlight library.
I am assuming that most of you might have already started using Silverlight 3 and have read our previous Silverlight 3 articles. This new version of Silverlight has lots of various new professional features. One of the new features is ‘Merge Resource Dictionaries’. Resource Dictionary is a facility using which styles and templates can be defined for various UIElements provided in Silverlight. Let us explore this feature in this article.
Step 1: Open VS 2008 and Create a new Silverlight 3 application. Name this as ‘SILV3_DynamicLoadingResourceDictionary’, you will get the ASP.NET web application along with the Silverlight application.
Write the following code in the .xaml – in my case MainPage.Xaml in the Silverlight 3 Project:
<Grid x:Name="LayoutRoot" Background="White" Height="700" Width="400">
    <Grid.RowDefinitions>
        <RowDefinition Height="100"></RowDefinition>
        <RowDefinition Height="300"></RowDefinition>
        <RowDefinition Height="300"></RowDefinition>
    </Grid.RowDefinitions>
    <ComboBox Grid.Row="0" x:Name="lstResourceDict" Height="50" SelectionChanged="lstResourceDict_SelectionChanged">
    </ComboBox>
    <Button x:Name="btnOne" Grid.Row="1"  Content="Button ------> 1"></Button>
    <Button x:Name="btnTwo" Grid.Row="2"  Content="Button ------> 2"></Button>
</Grid>
The above code adds a combobox and two buttons on the page. (Note: The ‘SelectionChanged’ event is specified here which will be used later).
Step 2:  In the Silverlight project, right-click and add a resource dictionary and name this as ‘ButtonStyle.xaml’.
Add_New_Item
Following is the Resource Dictionary file in the Silverlight project: ‘ButtonStyles.xaml’. For this .xaml file, the following properties are set:
Build Action: Content.
Copy to Output Directory: Copy if Newer.
<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style x:Key="RedKey" TargetType="Button">
        <Setter Property="Background" Value="Red"></Setter>
        <Setter Property="Height" Value="150"></Setter>
        <Setter Property="Width" Value="150"></Setter>
    </Style>
</ResourceDictionary>
 
The above .xaml file defines the style for the Button. The ‘x:Key’, here is used to read the style.
Step 3: In the solution, right click and add the Silverlight class library and name it as ‘SILV3_ExternalResourceDictionary’ as shown below.
Add_New_Project
Remove the Class1.cs from the project and add the following the code to the .xaml file:
<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style x:Key="RedKey" TargetType="Button">
        <Setter Property="Background" Value="Red"></Setter>
        <Setter Property="Height" Value="150"></Setter>
        <Setter Property="Width" Value="150"></Setter>
    </Style>
</ResourceDictionary>
 
Step 4: Now to load the XAML resource dictionary dynamically, in the Silverlight project add the following XML file and name it as ‘ResourceDictionaryStorage.xml’:
<?xml version="1.0" encoding="utf-8" ?>
<ResourceDictionaryData>
    <FileName Name="ButtonStyles.xaml" Value="RedKey"></FileName>
    <FileName Name="/SILV3_ExternalResourceDictionary;component/ExternalButtonStyle.xaml" Value="GoldKey"></FileName>
</ResourceDictionaryData>
 
Following are the properties set for the above xml file:
Build Action: Content.
Copy to Output Directory: Copy if Newer.
Step 5: Open the MainPage.Xaml file and at the class level, declare the following objects:
C#
       ResourceDictionary rd1, rd2;
       string rdName;
 
       XDocument xDoc;
       string resourceKeyName;
VB.NET
 Dim rd1, rd2 As ResourceDictionary
       Dim rdName As String
 
       Dim xDoc As XDocument
       Dim resourceKeyName As String
 
In the MainPage.xaml, the following code shown below is written in loaded event: (Note: Add the reference to System.Xml.Linq in the Silverlight project).
C#
//This will Read Keys Collection for the xml file
xDoc = XDocument.Load("ResourceDictionaryStorage.xml");
var KeyCollection = from file in xDoc.Descendants("ResourceDictionaryData").Elements("FileName")
                    select file;
 
foreach (var item in KeyCollection)
{
    lstResourceDict.Items.Add(item.Attribute("Value").Value);   
}
VB.NET
'This will Read Keys Collection for the xml file
xDoc = XDocument.Load("ResourceDictionaryStorage.xml")
Dim KeyCollection = _
      From file In xDoc.Descendants("ResourceDictionaryData").Elements("FileName") _
      Select file
 
For Each item In KeyCollection
      lstResourceDict.Items.Add(item.Attribute("Value").Value)
Next item
 
The above code loads the xml file and reads the attribute ‘Value’. This ‘Value’ reads the key of every xml element from the xml file and loads it in a ComboBox.
Step 6: Now in the ‘SelectionChanged’ event of the ComboBox, the values are read. This value represents the key of the resource dictionary style. This key is used to read style information set for a specific UIElement of the Silverlight.
C#
private void lstResourceDict_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
 
    rdName = lstResourceDict.SelectedItem as string;
 
    xDoc = XDocument.Load("ResourceDictionaryStorage.xml");
 
    //This will Read ResourceDictionary file
    var FileName = from file in xDoc.Descendants("ResourceDictionaryData").Elements("FileName")
                   where file.Attribute("Value").Value == rdName
                   select file;
 
    foreach (var item in FileName)
    {
        resourceKeyName = item.Attribute("Name").Value;
    }
 
    rd1 = new ResourceDictionary();
    rd1.Source = new Uri(resourceKeyName, UriKind.Relative);
    this.Resources.MergedDictionaries.Add(rd1);
    System.Windows.Style btnStyle = rd1[rdName] as Style;
    btnOne.Style = btnStyle;
 
    rd2 = new ResourceDictionary();
 
    rd2.Source = new Uri(resourceKeyName, UriKind.Relative);
    this.Resources.MergedDictionaries.Add(rd2);
 
    System.Windows.Style btnStyle1 = rd2[rdName] as Style;
 
    btnTwo.Style = btnStyle1;
 
}
 
VB.NET
Private Sub lstResourceDict_SelectionChanged(ByVal sender As Object, ByVal e As SelectionChangedEventArgs)
 
      rdName = TryCast(lstResourceDict.SelectedItem, String)
 
      xDoc = XDocument.Load("ResourceDictionaryStorage.xml")
 
      'This will Read ResourceDictionary file
      Dim FileName = _
            From file In xDoc.Descendants("ResourceDictionaryData").Elements("FileName") _
            Where file.Attribute("Value").Value = rdName _
            Select file
 
      For Each item In FileName
            resourceKeyName = item.Attribute("Name").Value
      Next item
 
      rd1 = New ResourceDictionary()
      rd1.Source = New Uri(resourceKeyName, UriKind.Relative)
      Me.Resources.MergedDictionaries.Add(rd1)
      Dim btnStyle As System.Windows.Style = TryCast(rd1(rdName), Style)
      btnOne.Style = btnStyle
 
      rd2 = New ResourceDictionary()
 
      rd2.Source = New Uri(resourceKeyName, UriKind.Relative)
      Me.Resources.MergedDictionaries.Add(rd2)
 
      Dim btnStyle1 As System.Windows.Style = TryCast(rd2(rdName), Style)
 
      btnTwo.Style = btnStyle1
 
End Sub
 
Step 7: Run the application, change the selection for the combobox and the following output will be displayed:
ComboBox_Selection

The entire source code of this article can be downloaded over here.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce the The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this eBook aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on .NET Standard and the upcoming C# 8.0 too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Mahesh Sabnis is a DotNetCurry author and Microsoft MVP having over 17 years of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions). Follow him on twitter @maheshdotnet


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by test on Friday, August 21, 2009 4:48 AM
good article
Comment posted by test on Friday, August 21, 2009 4:49 AM
hi

good article
Comment posted by margaret on Tuesday, August 25, 2009 12:14 AM

I recently came across your blog and have been reading along. I thought I would leave my first comment. I don't know what to say except that I have enjoyed reading. Nice blog. I will keep visiting this blog very often.

Margaret

http://grantsforeducation.info
Comment posted by russell on Tuesday, April 27, 2010 9:52 AM
hi,
I don't know why i get this error "Error HRESULT E_FAIL has been returned from a call to a COM component." on this line  
rd1.Source = new Uri(resourceKeyName, UriKind.Relative);

my project is located on a network.is this the problem!?

thanks for your helpful articles!
Comment posted by gonzalless on Friday, June 4, 2010 5:30 AM
hi,
i also get the error:
Error HRESULT E_FAIL has been returned from a call to a COM component.

regards.
Comment posted by gonzalless on Friday, June 4, 2010 6:44 AM
Solution is to modify uriString accordingly:
rd1.Source = new Uri("/[your project name];component/" + resourceKeyName, UriKind.Relative);

regards.
Comment posted by rocks2010 on Monday, December 5, 2011 2:09 PM
Yes, well written article. I could find out some useful information on your blog guys. This is really useful for everyone. I love this post. Thanks for sharing it.
Comment posted by rocks2000 on Monday, December 5, 2011 2:09 PM
This looks cool. Good strong lens here..It actually does work have used it.
<a href="http://www.thesiswritingservice.com">thesis writing service</a>
Comment posted by term paper for sale on Tuesday, October 23, 2012 12:11 AM
There are true offence bolgs which are pestering to cater this nurturant of plausive increase, your production is the somebody of all. i appriciate your compliments.
<a href="http://www.essaystermpapers.com/original-term-papers-for-sale/">term paper for sale</a>
Comment posted by Essay Writing Service on Monday, June 3, 2013 5:17 AM
It's Very Interesting. Enjoy it's reading


<a href="http://www.essayleaks.com/Write-My-Essay.aspx">Write my essay online </a>
<a href="http://www.essayleaks.com/Buy-Research-Papers.aspx">Buy Research paper</a>
<a href="http://www.essayleaks.com/Research-Paper-Writing-Service.aspx">Research Paper Writing Service</a>
<a href="http://www.essayleaks.com/paper-writing-service.aspx">Paper Writing Service</a>
<a href="http://www.essayleaks.com/Buy-Essay.aspx">Buy Essay writing help</a>
Comment posted by Custom essay writing service on Monday, June 3, 2013 6:54 AM
Wow what a great post.  This is why I read this blog.   This is very actionable and something a real business would do!   I love it!


<a href="www.essaywonder.com/argumantativeEssay.php">Custom Argumentative Essay Services</a>
<a href="www.essaywonder.com/schoolpapers.php">High School Research Paper</a>
<a href="www.essaywonder.com/buyessaypapers.php">Essay Paper Writing Services</a>
<a href="www.essaywonder.com/cheapessays.php">Cheap Essay Writing Services</a>

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

C# .NET BOOK

C# Book for Building Concepts and Interviews

Tags

JQUERY COOKBOOK

jQuery CookBook