Wednesday, December 22, 2010

Extracting A ControlTemplate From An Existing WPF Control

There are a number of tools to do this, not least of which is Blend.  But sometimes you need some code to do it for you.  There have been a few instances where Blend was unable to extract the control template, and resorting to code is the last line of defense.

Here's a snippet of code from a test application where Group1 is an element (of type RibbonGroup).  This code comes from a code behind from a xaml window.

var template = this.Group1.Template;
            var xmlSettings = new XmlWriterSettings { Indent = true };

            var builder = new StringBuilder();
            XmlWriter writer = XmlWriter.Create(builder, xmlSettings);
            XamlWriter.Save(template, writer);
            Clipboard.SetText(builder.ToString());
            Debug.WriteLine(builder.ToString());
This will output the control template xaml to the Debug output and also copy it to the clipboard.

No comments:

Post a Comment