Charles Petzold on writing books, reading books, and exercising the internal UTM

Recent Entries
< PreviousBrowse the ArchivesNext >
Subscribe to the RSS Feed

Article on Custom Controls and Templates

December 26, 2007
Roscoe, N.Y.

The January 2008 issue of MSDN Magazine is now online, including my article Templates for Uncommon Controls.

Creating a WPF custom control is fairly easy: Just derive from UserControl and define the control's visual tree as the Content property.

Creating a new template for an existing control is also fairly easy: Just replace the Template property with a custom visual tree.

However, as I discovered while writing this article, creating a custom control with a replaceable template is not so easy. In theory, all you need to do is derive from Control and define a default Template property. It turns out there are special requirements if you want to put this custom control in a DLL (as you probably do) and there are several standard techniques for making the template accessible from the control's code.

If you want to create custom controls and allow other programmers to replace the control's template with one of their own design, this article is for you.


Sorry to dig up old posts, but I'm trying to learn all I can about developing custom controls before I begin a new project, and your book and articles have been the most helpful to me by far.

In chapter 11 of your book you create a template for a Button control completely in code (using no XAML). Will this method not create a replaceable template? This post (and the referenced article) seem to imply that you must use XAML to create a replaceable template.

I'm not trying to avoid XAML, I'm just trying to understand the difference.


Tad Smith, Wed, 12 Nov 2008 14:29:21 -0500 (EST)

The generic.xaml file must have a root element of ResourceDictionary containing (or referencing) a Style for the control. This Style in turn references the control's default template. I suspect it might be possible to create the template in code, and then attach it to the Style template, but I've never tried that. — Charles

Recent Entries
< PreviousBrowse the ArchivesNext >
Subscribe to the RSS Feed

(c) Copyright Charles Petzold