Skip navigation links
Home
Document Center
Blog
Videos
Forum
PhillyXAML.org > Blog > Categories
How can I create or even view a Control Template if I do not own Expression Blend?
Have you ever tried to write a Control Template without having access to Expression Blend? Its pretty tough to say the least. For one, many of the controls are hard to get to, specifically those nested inside other Control Templates. The problem is compounded when items inside the template need to have specific names in order for the control to render correctly. For example, many controls, when written, use a mechanism by which during the OnApplyTemplate() call, a control is loaded using FrameworkElement.FindName(string controlName), in order to add event handlers.
 
Use the code snippet below to get the Control Template for a Control as a XAML string. Simply pass in the Control.Template object.

        private string GetTemplateString(FrameworkTemplate template)
        {
            if (template != null)
            {
                // Create XmlWriter Settings. We need the XmlWriter for
                // the XamlWriter.Save() call
                XmlWriterSettings settings = new XmlWriterSettings();

                // Shows User-Friendly XML output with indents (tabs, sp, etc.)
                settings.Indent = true;

                // use space character 4 times for the tab. \t
                settings.IndentChars = new string(' ', 4);

                // Shows all attributes as new lines
                settings.NewLineOnAttributes = true;

                // StringBuilder to act as output container
                StringBuilder strbuild = new StringBuilder();

                // Create the XmlWriter from the settings,
                // using the StringBuilder as output container
                XmlWriter xmlwrite = XmlWriter.Create(strbuild, settings);

                try
                {
                    // Try writing the ControlTemplate XAML to the XmlWriter, 
                    // which populates the StringBuilder downstream
                    XamlWriter.Save(template, xmlwrite);

                    // Return the StringBuilder text
                    return strbuild.ToString();
                }
                catch (Exception exc)
                {
                    // Display Exception that occurs
                    return "EXCEPTION: " + exc.Message;
                }
            }
            else
            {
                // Template is null
                return "Template is [null]";
            }
        }

Alternatively you could change the method signature to be GetTemplateString(Control c).
This may make it a little easier to read, since the implied functionality is to get the Template string based on a Control, not the template itself as the method above indicates. Add the following line immediately after the opening braces.
 
FrameworkTemplate template = c.Template;