Supporting Templates in Custom Controls

The final design consideration for any custom element is how it will connect with its visuals. If the element derives directly from FrameworkElement, it might be appropriate for it to generate its own visuals. (Chapter 13 described how to create a graphical appearance.) In particular, if you are creating an element whose purpose is to provide a particular form of visualization—such as an element that renders a three-dimensional graph—the element should take complete control of how this is managed. However, if you are writing a control, you would not normally hard-wire the graphics into the control.

Remember that a control's job is to provide behavior. The visuals are provided by the control template. A control may provide a default set of visuals, but it should allow these to be replaced in order to offer the same flexibility as the built-in controls. (Chapter 9 described how to replace a control's visuals with a template.) A control that conforms to this approach, where the visuals are separated from the control, is often described as lookless, because the control has no intrinsic appearance or "look." All of the controls built into WPF are lookless.

Of course, it is not possible for the control to be entirely independent of its visuals. As we saw in Chapter 9, there is an implied contract between a control and its template. The control allows its appearance to be customized by replacing the template, but the template should in turn provide ...

Get Programming WPF, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.