An Extension Method to Dump Control Templates of WPF Controls

By Anoop Madhusudanan

Vote on HN

In Blend, you have the ability to create a copy of the control template of a control, and edit it (Right Click – Edit Template – > Edit A Copy). If you are interested, you can dump the Control template of any given WPF control pretty easily, from the source code as well.

Here is a simple extension method to dump the control template of a WPF control.

 public static class ControlTemplateExtension 
         public static string DumpControlTemplate(this Control ctrl)
            XmlWriterSettings settings = new XmlWriterSettings()
                Indent = true,
                NewLineOnAttributes = true

            StringBuilder strbuild = new StringBuilder();
            XmlWriter xmlwrite = XmlWriter.Create(strbuild, settings);
            XamlWriter.Save(ctrl.Template, xmlwrite);
            return strbuild.ToString();
And now you can go ahead and dump your control templates, like this.

   //use your control name instead of mybutton
   var strXaml = this.myButton.DumpControlTemplate();
   //Do something with your control template
Shout it
© 2012. All Rights Reserved.