Tag Archives: IsThreeState

RadioButton and IsThreeState

21 Oct

CheckBox and RadioButton both inherit from ToggleButton. ToggleButton contain a bool property called IsThreeState. It enables the control to have three different values: true, false and null. This functionality is handled automatically by the CheckBox control:

2010-10-21_214156

It’s a different story for the RadioButton control. Actually it’s against the nature of a RadioButton to hold a null value and to be able to uncheck it once it’s checked (unless another RadioButton is checked). It’s the same reason that we will never be able to set the IsChecked value to null by clicking it but only by setting it initially.

Even though it’s not logical it’s possible to achieve the same functionality in a RadioButton control as a CheckBox control. First step is to create a new custom control and inherit from RadioButton. Second step is to override the OnClick eventhandler. In the OnClick eventhandler we need to manually handle the three steps that IsChecked can achieve. Finally we need to create a custom style that is set in the constructor.

2010-10-21_220020

In the ControlTemplate we have to implement the visual elements that should be shown when the RadioButton is in indeterminate state.

With the style in place we now have the full IsThreeState functionality:

2010-10-21_220358

You can download the sample project here: http://bit.ly/ajSdEj

by xamlgeek
twitter.com/thomasmartinsen