#102 – Using XamlReader to Load a Loose XAML File

When you use Visual Studio to create the main Window, App and Page XAML files that make up a WPF application, code is automatically generated to cause the XAML (BAML) files to be read at runtime.

You can also use the XamlReader class to read loose XAML files–ones that have not be converted to BAML and stored as a resource in your application.

The static XamlReader.Load method will read a XAML file, instantiate all objects defined in the file, and return a reference to the top-level (root) element from the file.  (XamlReader is in the System.Windows.Markup namespace).

Assuming that you have a XAML filed named Stuff.xaml and it has a root element that is a StackPanel, you could load the file as follows:

 StackPanel sp1;
 using (FileStream fs = new FileStream("Stuff.xaml", FileMode.Open))
 {
     sp1 = (StackPanel)XamlReader.Load(fs);
 }
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

3 Responses to #102 – Using XamlReader to Load a Loose XAML File

  1. Prakash says:

    Can I have a common set of repeatable elements in a separate XAML file, and then use XamlReader.Load to read that XAML, create the contents, and inject it into the UI at runtime?

Leave a Reply

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

WordPress.com Logo

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

Facebook photo

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

Connecting to %s

%d bloggers like this: