Siverlight: loading XAML files

Currently, we”re limited in the ways we can open XAML files. Even though there”s a File API on the mini-CLR platform that is used by Silverlight alpha, most of its methods are marked as SafeCritical, which means you can”t just call them from your code. This isn”t really a big issue if we”re talking about files you control. In these cases, you can embed  the file on your dll and then load it at runtime. For instance, if you”re following the control approach (which is used by some of the Silverlight samples), then you”ll be doing something like this (writing it here so that you don”t need to go to the site to look at it):

Stream xamlStream = this.GetType().Assembly.GetManifestResourceStream( complete_resource_name_goes_here);
rootReference = this.InitializeFromXaml( new StreamReader( xamlStream ).ReadToEnd() ) as Canvas;

Ok, that”s cool, but what happens when you need to load xaml and add it to an existing canvas? In that case, you need to get the xaml in text format and pass it to the Load method of the XamlReader class. Reusing the previous example, you”ll end up with something that looks like this:

Stream xamlStream = this.GetType().Assembly.GetManifestResourceStream( complete_resource_name_goes_here);
string xaml = new StreamReader( xamlStream ).ReadToEnd();
Canvas aux = (Canvas)XamlReader.Load( xaml );

And that”s all there is to it.


~ by Luis Abreu on May 29, 2007.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: