RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


WPF Wonders: Building Control Templates

WPF's properties and styles let you change a control's appearance. Templates let you modify a control at a much more fundamental level, changing the components that make up the control and the way it acts. This article shows how you can use templates to change the fundamental structure of WPF controls.


PF's XAML language defines the controls that make up a user interface. Typically, some kind of container control such as a Grid or StackPanel fills the window. In turn, that container holds other controls, such as Labels, TextBoxes, Buttons, Sliders, and so forth.

Your XAML code defines the user interface's structure and—to an extent—its behavior. For example, you can define animations in XAML that change control properties such as size and position when certain events occur.

WPF also lets you use templates to define the structure of the controls that make up the interface. By controlling the structure of a Slider, for example, you can change the way it looks and acts. For example, you could use a template to make a Slider display round buttons on its ends, a thin track in the middle, and a fat diamond-shaped thumb for dragging.

This article describes templates, explains how to build and use them, and provides a few useful examples.

What Is a Template?

Figure 1. Slider Dissected: If you look closely at a WPF Slider control, you'll see that it's a composite, made up of lots of parts that are actually other controls.

If you look closely at most controls, you'll find that they're made up of a number of parts. Figure 1 shows a Slider control with its constituent parts marked.

You might imagine that a single chunk of code makes up the Slider and creates all of these pieces, but that's not the case. The Slider is made up of an assortment of other controls, including Border, Canvas, Grid, Path, Rectangle, RepeatButton, Thumb, TickBar, and Track controls. For example, the TickBar control draws the tick marks and the Thumb allows the user to click and drag the thumb. Together, those individual controls determine the Slider control's appearance and behavior.

The control's template determines the Slider's pieces and how they behave. It defines the sub-controls that make up the Slider and determines how they interact with the user through the sub-controls' properties.

This would all be only mildly interesting if it weren't for the fact that you can change a control's template. If you want to build an elliptical Slider that lets the user drag a circle around the ellipse's rim, you can! You'll have to define how the new template provides a Slider's typical behavior—but you can do it if you really want to.

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date