Tuesday, 27 March 2012

WPF Custom Control with Image

In this example we are going to create a custom control in WPF called MetroTile.

Our MetroTile control will expose three properties to let designers set an image icon, a display count and a text property. The usual core properties for controls are also settable such as background, foreground, margin, etc.

This screenshot shows three instances of the custom control in use, all with the generic template applied. The RabbitMQ and ZeroMq tiles override the default background.

Class Diagram

Key concepts

Three dependency properties that allow the Xaml data binding system to do its work.

I’ve also shown how to expose a bubbling RoutedEvent (travels up the visual tree until handled) through the DisplayCountChanged event. As is common, I’ve included a Preview RoutedEvent that tunnels down the visual tree, which fires just before the main event.

A public RoutedUICommand called ResetCountCommand is also included which you can bind to from Xaml. Commands are preferred to methods as you cannot bind directly to methods.

MetroTile Custom Control

Default Template

The display icon is located in top left hand corner when set by the developer using the custom control. When the developer first includes the control in their xaml, the following default values are visible on their design surface:

protected virtual void OnDisplayCountChanged(int oldValue, int newValue) { // 1. Pair of events: A preview that tunnels and a main event that bubbles // 2. We could also create our own RoutedEventArgs that includes oldValue & new Value