I am .NET developer following it from the first PDC. I love to work on CLR related stuff, Interop and WPF related areas. I design software and I love to design reusable and extensible frameworks. I am married to the love of my life and living in Dhaka, Bangladesh. Shafqat has posted 10 posts at DZone. You can read more from them at their website. View Full User Profile

WPF Kid Stuff: Extracting a Control Template

  • submit to reddit

One of the design principles for WPF was to enable the developer decide the look and feel of the control and that resulted in the most versatile UI framework that can be customized in any way the developer wants. Previously there were many widgets for different languages and frameworks because their look could not be customized beyond the method the control builder provided. With the help of templates in WPF that has changed and that is why there are a lot less custom controls in WPF than the previous technologies. In order to customize something the end developer has to only modify the templates.

If we want to modify a the default look of a controls that is not controllable by the properties, the best way to do that is to extract the existing template of the control and change that. Manually we could open up Expression Blend and right click on a control end edit a copy of the template. See image below.

This would actually reveal the control template that builds control and we can modify it and use as we please.

Another procedure is the extract the template from code is to get the template from the control itself. We can write c# code to extract the template like this …

// Get the template from the control 
ControlTemplate template = ctl.Template;

// We want our xaml of be properly indented, ohterwise
// we would not be able to indent them.
XmlWriterSettings xmlSettings = new XmlWriterSettings();
xmlSettings.Indent = true;

// Make the string builder
StringBuilder sb = new StringBuilder();
XmlWriter writer = XmlWriter.Create(sb, xmlSettings);
XamlWriter.Save(template, writer);

// Now the sb.ToString() should give us the template

Note: There will be more controls in the xaml template output. Their templates can be extracted further.


Published at DZone with permission of its author, Shafqat Ahmed. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)