How can I get the actual XAML from a template object in code (or can I)?

2.4k Views Asked by At

Not sure if this is possible, but if I have a template object (passed in to the OnApplyTemplate override) is there any way I can examine the string-representation of the XAML that makes it up? I know internally when the template's XAML gets compiled, it's actually converted to BAML, and I know by the time the code gets to the override, it's neither as it's already rehydrated into actual objects, which is why I'm asking.

Actually, if you can go from a template object to XAML, couldn't you then theoretically go from any WPF object to it's XAML representation? I'd settle for the former of just a template however.

This is C# in .NET 4.0, not Silverlight FWIW.

M

1

There are 1 best solutions below

0
On

The old XamlWriter class works most of the time. The new XAML classes, in System.Xaml, throw an error for some reason when trying to serialize a ControlTemplate to XAML. I suggest you avoid relying on any XAML writing in production code...

var template = this.FindResource("MyTemplate") as ControlTemplate;

// The new XamlServices class throws an error. 
//string xaml = System.Xaml.XamlServices.Save(template);

// The old XamlWriter from the Markup namespace works (usually)
string xaml = System.Windows.Markup.XamlWriter.Save(template);

// Format the XAML so that it's readable.
string indentedXaml = XElement.Parse(xaml).ToString();

Console.WriteLine(indentedXaml);