How can I decompile/extract a WPF Control's default template as Xaml?

The rendering of controls in WPF is defined by the template used for the control. In a previous posting we saw how to supply our own template for a control to customize the rendering. It is not un-common to want to make some small modifications to the default template for an existing control, or wonder how a certain effect is achieved in the default template of a given control. Wouldn't it be great if you could somehow extract the Xaml code for default template out of a control and see how it worked? Fortunately in WPF you can, using a technique I first heard about from WPF evangelist Karsten Januszewski. The steps are as follows:

  1. You add an add an instance of the control you want to "decompile" to your form and give it a name. In this example we've assumed it will be named controlIWantToDecompile.
  2. Add a window loaded or button click event handler to your form. Inside the event handler add the following snippet of code:
    StringBuilder sb = new StringBuilder();
    using (TextWriter writer = new StringWriter(sb))
    {
        System.Windows.Markup.XamlWriter.Save(controlIWantToDecompile.Template, writer);
    }
  3. Write the contents of the string builder to the debug output, or out to a text box. You now have the default template for the control.

You can then add this newly extracted template as a resource, and have control instances to use it, or add it as part of a style. Using the same technique you can also serialize out a control's default style (if it has one). Here is a screen-shot of two check-boxes. The first is a regular xp-themed WPF checkbox. The second one uses a slightly modified version of the normal checkbox template. We "extracted" the default template using the method described above and then made a few small modifications, without having to re-create the mouse-over behavior or the check mark ourselves.

Two checkboxes, one with the default XP theme and one slightly modified

This ability to look at and modify the default templates for controls is so useful that it is built right in to the Expression Interactive Designer (code-named Sparkle). In the March 2006 CTP right-click on a control and select Edit Template > Edit a Copy of the Template (as shown below).

Menu from Sparkle

You are then presented with a dialog prompting you for the name of the new template you wish to create, where you wish to locate the resource and what type the template should target. You can then edit the template with the same great graphical designer experience you have for editing regular forms (or edit the Xaml directly is you wish).

sparkle dialog

This ability to extract and serialize out as Xaml the default template for a control is invaluable when you're trying to create a template for a complex control like a slider or combo box. It is also useful to see some of the techniques used by the WPF team themselves when creating control templates.