Wednesday, December 10, 2008

[C#] Loading embedded XAML files into a project

I was looking for a way to load in a XAML file into my project; I wanted to be able to create a nice looking element without having to build it up dynamically in the C# code, and without having to download the XAML file from a server as I have been doing in some other places.

Turns out you can embed a file as a resource in a Visual Studio project and then open the resource and stream it out!
Step 1: Right click on your project folder and add the new or existing resource to your project.

Step 2: Right click the newly added file in your solution explorer, and select "Properties"

Step 3: Change the "Build Action" to "Embedded Resource". Now the file will be built in to your project as a resource and accessible as such.

Step 4: Open up a stream to the resource, read it out into a string and then use XAMLReader.Load to load up the element. I found this code on a forum, so there may be an easier way to do it... but this worked for me.

Stream s = this.GetType().Assembly.GetManifestResourceStream ("myNamespace.myFile.xaml");
string propertyStr = new StreamReader(s).ReadToEnd();
Panel myGrid = (Panel)XamlReader.Load(propertyStr);

And BAM... loaded xaml! Note that your XAML file must contain the namespace information in order for [System.Windows.Markup.]XAMLReader.Load to load correctly.

Example myFile.xaml:
<. Grid
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<. /Grid .>


Have fun :)
.

No comments: