Site Logo

Pixel-in-Gene

Exploring Frontend Development with Design / Graphics / Technology

Recommended practices for WPF Custom Control developers

I have always found that there isn’t enough documentation about Custom Control development in WPF. Most of the information is segregated into articles, blog entries and posts on the WPF Forums. In order to save the trouble for other fellow WPF developers I intend to document all my findings at one place: this blog. To start with, there are some articles which are a must read for all control developers:

  1. Control Authoring Overview
  2. Kevin Moore’s article on ColorPicker control
  3. Creating lookless control
  4. Control Styling Guidelines [Update: Added link]

Below are some of the practices which I found useful when creating my own custom controls.

Event-handling practices:

  • Use RoutedEvents, Commands and CommandManager
  • Use TemplatePartAttribute
  • Name the controls that are used inside the custom control with something like “PARTSubControlName”. The **PART\** prefix is a convention.
  • This is useful if you want your control to be styled using a Designer. I am not aware of the exact semantics of how this is used.
  • Specify the TemplatePartAttribute for the custom control class
  • Override OnApplyTemplate() and check for existence of the subcontrols in use. Check using the GetTemplateChild() method. If a part by that name is absent, throw an exception.
  • Attach event handlers on the sub control

Theming practices:

  • Create a ResourceDictionary called generic.xaml. Create a folder named themes in your library and put generic.xaml inside that.
  • Organize multiple resources using MergedDictionaries [Article]
  • Override the DefaultStyleKeyProperty inside the custom controls static constructor.
  • Use ComponentResourceKey on specific resources used within the custom control. It is used to embed resources as part of the control.

I will make more posts as I learn about other practices. I am open to feedback from other developers. In future posts I should have more information about Databinding, Localization practices.

Recommended practices for WPF Custom Control developers
Pavan Podila
Pavan Podila
August 26th, 2006