WPF Kid Stuff: Extracting a Control Template
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);
// 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.
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)