#102 – Using XamlReader to Load a Loose XAML File
October 22, 2010 3 Comments
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); }
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?
Yes, you can do this. Take a look at:
Dynamically Loading XAML
Loading XAML at Runtime
Here’s another good article – Dynamically Generating Controls in WPF and Silverlight