#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