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:
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.
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:
You can download the sample project here: http://bit.ly/ajSdEj
Good post. I found it useful as I have a client application with the need to input scores for a test given on paper to the system. I needed both the functionality of a radio button and a checkbox at the same time. I overrode the OnMouseLeftButtonDown event however as I had a command bound to the click event. I also need to override the OnClick event to prevent the default functionality from changing the IsChecked property back to its bound value. In the override I just called execute on the Command and passed it the CommandParameter.
Great Job!
Ok, as i was reading what I had posted and did I thought how stupid of me to override both methods. I refactored my code and moved all of the code from the mouse event to the click event and it works the same. I hate it when I think like that.
Good job still even though someone like me can dork it up.
This solution does break the RadioGroup functionalty which is the core of the radiobutton. Shame.