XAML has this great concept of look-less controls. When we see a normal Win32 control like say a checkbox, we always assume that it will be a square box along with some text written to the left of it. Taking an example from our old friend WordPad, we would always expect a checkbox to look like
Pretty boring, if you would ask a kid (or even a teenager!). Even though it makes the control much more usable (which is a very important thing BTW), it doesn’t look cool. So how does WPF help us here?
For starters, when you define a control, WPF doesn’t force to you to define the look of the control along with the functionality. Here comes the concept of a look-less control; a control whose behaviour is defined but whose look is not defined. For instance, we might define the behavior of the check box (it has a bool or a bool? property called IsChecked, it has a check mark to the left of the content, etc… 😉 but leave it to the author to define the look for it. So we might have something like
How to go about doing this? This is all done by redefining the ControlTemplate for the checkbox. ControlTemplate is basically what it says, it is a Template for the Control and decides how the control will look like. To achieve such a look we define the Style of the Checkbox as
Let us dissect this monster to see how it works 🙂
The first line
means that this is a Style being defined for Type CheckBox in the namespace referred to by x which is http://schemas.microsoft.com/winfx/2006/xaml in my case.
Moving on, the core part of the Style is in defining the ControlTemplarte.
Note that I could have defined the ControlTemplate for the CheckBox using CheckBox.ControlTemplate but have chosen to implement it using a Style as it is quite common to do so.
It is in this ControlTemplate that I define the look of the CheckBox. Here I say that it should be a WrapPanel which should contain a Border which has an Image and a ContentPresenter in it. You can read more about the ContentPresenter in MSDN, it is just a UIElement which can contain and display any other object. The Image has a binding to the Height of the ContentPresenter so that it resizes automatically to the Height of the content, else you might have a case when you have text with FontSize 36 points but you checkmark is just 10 pixels high. That’s it! That’s the definition of our customized CheckBox; could it be any easier?
I added some Triggers to change the Image in the CheckBox depending on its state. I have added an image when IsChecked is null to account for a Tri State CheckBox. I also added some BitmapEffects for a Glow (just to make it more pretty!)
Go through the code, it isn’t very hard to understand or comprehend. Now whenever you wish your CheckBox to use this style, simply use it as
If you find this article useful, do comment and let me know