There are occasions that you might need to load and parse the xaml file and you hope that you can get some UIElement out of it, or even more sophisticated if you can load and parse any Xaml elements. And ther might also be occasions where you wantted to do the reverse, where you have a Control (or a VisualTree in general) and you want to cast that back to some serialized form, such as xaml code..
However, this is not yet possible for every type of the Xaml, but notheless, we will examine some guideline code on how you can do such as thing.
Suppose that you have a Buton declared in a xaml file, and the declaraion is like this:
<Button Background="#FFF0F8FF" Width="100" Height="50" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">Click Me</Button>actually this file is saved by XamlWriter.Save(UIElement) call.
and we can use the following code to load the button up from the Serialized xmal file. Here is the code.
UIElement rootElement; FileStream s = new FileStream(fileName, FileMode.Open); rootElement = (UIElement)XamlReader.Load(s); s.Close();
And you are also fine to use the XamlWriter to savea exisitng Control back to a Xaml file, here is the code snippet.
Button originalButton = new Button(); originalButton.Height = 50; originalButton.Width = 100; originalButton.Background = Brushes.AliceBlue; originalButton.Content = "Click Me"; // Save the Button to a string. string savedButton = XamlWriter.Save(originalButton);and the saved form is verified by the Load call
// Load the button StringReader stringReader = new StringReader(savedButton); XmlReader xmlReader = XmlReader.Create(stringReader); Button readerLoadButton = (Button)XamlReader.Load(xmlReader);And remember we said the Xaml is saved to a file:, here is the code
using (FileStream fs = new FileStream(@"C:\dev\workspaces\dotnet\microsoft\wpf\src\assemblies\xaml\LoadingXaml\Data\ButtonOutput.xaml", FileMode.OpenOrCreate, FileAccess.Write)) using (StreamWriter texWriter = new StreamWriter(fs, Encoding.UTF8)) { texWriter.Write(savedButton); }
There is still limit as what you can do with Xaml dynamical load, you cannot do with any Xaml elemen for one, and accoring to my test, the xaml with codebehind cannot be loaded.. Haven't try to save such one..
Reference:
Loading XAML at runtime: