views:

103

answers:

3

Hi,

I would like to get the XAML source of a WPF Window (MainWindow). Clicking on a button on that window would return the XAML of the window and I would save it in another file.

Is this possible and how can it be achieved?

Thanks!

Satixx

+2  A: 

You can use XamlWriter for some basic Xaml Serialization. In particular, look at this article on its limitations.

Erich Mirabal
Thank you for your doc about the solution!
+2  A: 

You can use the XamlWriter:

using (Stream stream = File.OpenWrite("D:\\Test.xaml"))
{
    XamlWriter.Save(this, stream);
}
winSharp93
Thank you for your solution!
A: 

The earlier answers are both correct, but I think it should also be mentioned that you can also extract the original XAML used to create the window (if desired) using the API for Reflector's BAMLViewer extension.

BAMLViewer solves a different problem than XamlWriter: Using Reflector / BAMLViewer will return the original source XAML with all bindings, etc intact but will not include current property values. Using XamlWriter will include current property values but such things as resource references and markup extensions will be lost. Also, some things will not serialize using XamlWriter.

You must choose between these based on your application needs.

Ray Burns