Bookmark and Share Share...    Subscribe to this feed Feed   About Christian Moser  


Radio Button

Introduction

The RadioButton control has its name from old analog radios which had a number of programmable station buttons. When you pushed one in, the previosly selected poped out. So only one station can be selected at a time.

The RadioButton control has the same behavior. It lets the user choose one option out of a few. It the list of options gets longer, you should prefer a combo or list box instead.

To define which RadioButtons belong togehter, you have to set the GroupName to the same name.

To preselect one option set the IsChecked property to True.


 
<StackPanel>
    <RadioButton GroupName="Os" Content="Windows XP" IsChecked="True"/>
    <RadioButton GroupName="Os" Content="Windows Vista" />
    <RadioButton GroupName="Os" Content="Windows 7" />
    <RadioButton GroupName="Office" Content="Microsoft Office 2007" IsChecked="True"/>
    <RadioButton GroupName="Office" Content="Microsoft Office 2003"/>
    <RadioButton GroupName="Office" Content="Open Office"/>
</StackPanel>
 
 

How to DataBind Radio Buttons in WPF

The radio button control has a known issue with data binding. If you bind the IsChecked property to a boolean and check the RadioButton, the value gets True. But when you check another RadioButton, the databound value still remains true.

The reason for this is, that the Binding gets lost during the unchecking, because the controls internally calls ClearValue() on the dependency property.

 
<Window.Resources>
   <EnumMatchToBooleanConverter x:Key="enumConverter" />
</Window.Resources>
 
 
<RadioButton Content="Option 1" GroupName="Options1" 
             IsChecked="{Binding Path=CurrentOption, Mode=TwoWay, 
                                 Converter={StaticResource enumConverter},
                                 ConverterParameter=Option1}"  />
<RadioButton Content="Option 2" GroupName="Options2" 
             IsChecked="{Binding Path=CurrentOption, Mode=TwoWay, 
                                 Converter={StaticResource enumConverter},
                                 ConverterParameter=Option2}"  />
<RadioButton Content="Option 3" GroupName="Options3" 
             IsChecked="{Binding Path=CurrentOption, Mode=TwoWay, 
                                 Converter={StaticResource enumConverter},
                                 ConverterParameter=Option3}"  />
 
 
 
public class EnumMatchToBooleanConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, 
                              object parameter, CultureInfo culture)
        {
            if (value == null || parameter == null)
                return false;
 
            string checkValue = value.ToString();
            string targetValue = parameter.ToString();
            return checkValue.Equals(targetValue, 
                     StringComparison.InvariantCultureIgnoreCase);
        }
 
        public object ConvertBack(object value, Type targetType, 
                                  object parameter, CultureInfo culture)
        {
            if (value == null || parameter == null)
                return null;
 
            bool useValue = (bool)value;
            string targetValue = parameter.ToString();
            if (useValue)
                return Enum.Parse(targetType, targetValue);
 
            return null;
        }
    }   
 
 




Last modified: 2010-08-26 20:42:54
Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments
Carlos
Commented on 8.March 2010
Thank you, this example is just what I needed and nothing more. The people who don't understand need more background reading. Perhaps read about MVVM so the binding, converter make sense.
Andreas
Commented on 18.March 2010
This tutorial is worth pure gold! Just what I needed.
Olion242
Commented on 2.April 2010
Very good! Just what I needed.
Praveen
Commented on 11.May 2010
Amazaed to see so many dumb People. They are reading this and they dont know what data binding is.

It would have been better for lame user to understand if it had the solution/source code file with this in zip.
Praveen
Commented on 11.May 2010
Amazaed to see so many dumb People. They are reading this and they dont know what data binding is.

It would have been better for lame user to understand if it had the solution/source code file with this in zip.
Danube210
Commented on 12.May 2010
Thanks Robert and Adam for making it work :)
rahul bhojane
Commented on 3.June 2010
It's usefule. but not details explination
Great thanks

Caleb
Commented on 5.June 2010
Uh... to all the people saying "if people don't understand, too bad, figure it out yourself"

This is a TUTORIAL. The purpose of which is to teach. If it doesn't fulfill it's purpose, whats the point? If you're so smart, why are you looking up tutorials? Shouldn't you all "figure it out yourself"?
Robert
Commented on 14.June 2010
This worked well for me. You just have to remember to fire a PropChanged event in the set path of CurrentOption property (which is of type enum and not string as suggested, above).
atul
Commented on 16.June 2010
Hi can any one tell me how to enable/disable a button by select a checkbox. :)
Phill
Commented on 24.June 2010
This was very useful.

Effectively the built-in radiobutton functionality is not used at all really (the radiobuttons are all in their own group and the mutual exclusivity is an effect of the binding).

In the end I varied from the example a bit in that I found it safer to isolate each RadioButton from the others by putting each within its own parent (ie each in its own StackPanel) and not setting a GroupName at all. The use of GroupName was an issue for me when multiple copies of the same view where shown within a docking window...ie the radiobuttons from different view instances were interfering with each other.. this is not an issue when using a different parent for each radiobutton as a means of seperating them into different groups...
Alexander B
Commented on 19.July 2010
I am terribly confused by this tutorial. I followed the instructions exactly, but my databound value is not being updated when the radio buttons are clicked. Similarly, when I set all of the Group names to be identical, the unselected radio buttons become red bordered.
Todd Fisher
Commented on 26.August 2010
I believe one issue with having to use multiple group names is that the tabbing behavior does not operate correctly. If one of the radio buttons is set, the tab key should move you out of the group. However, since we have mutiple group names, we move to the next radio button.
swapnil
Commented on 30.August 2010
Hi,

Got the things implemented in tutorial.
Can we pass the content of radio button to converter class some how?
My requirement is that i want to get text of radiobutton just checked in the view model
Please help me out with this.
Thanks in advance.
Swapnil


swapnil
Commented on 30.August 2010
Hi,

Got the things implemented in tutorial.
Can we pass the content of radio button to converter class some how?
My requirement is that i want to get text of radiobutton just checked in the view model
Please help me out with this.
Thanks in advance.
Swapnil


Lee D
Commented on 5.September 2010
@Alexander B,

The red border is appearing because the ConvertBack is [correctly] returning null - which I believe WPF is interpreting as a validation error (trying to set an enum value i.e. the bound property, to null). After fighting with this myself the last two days, I found that if you simply redefine the Validation.ErrorTemplate for the RadioButton to be empty than you can remove the red border.

So, in a style that's applied to your RadioButtons:

<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate>
</ControlTemplate>
</Setter.Value>
</Setter>

Lee.
starbros47
Commented on 27.November 2010
"If you bind the IsChecked property to a boolean and check the RadioButton, the value gets True. But when you check another RadioButton, the databound value still remains true." I am using WPF 4.0 with .net 4.0, this issue is fixed.
Enhakiel
Commented on 15.January 2011
Hi, first thanks a lot. But I've got a little problem, I have a tabControl and each tabItem have a different opacity, on right click it open a context menu with radion button witch allow to change it, everything goes right, on each tabControl radiobutton is set to the correct value, but as soon as I changed a value (it's correctly set) if I click on another tabItem (the opacity is still ok) the context menu show the opacity I've set the the last one... have you got a solution? Thank you in advance
Ristogod
Commented on 8.February 2011
I've tried this technique and it does not work at all. Instead it simply allows any radio button to be checked, and it cannot be unchecked. So after clicking on each radio button, they all eventually get checked with no way to undo it.

Also, the ConvertBack never occurs. This because the Binding on IsChecked mysteriously disappears.

I'm using version 4.0. And I've yet to find a working solution to this problem.
Tuan Nguyen
Commented on 28.March 2011
This is great article. You also need to elaborate that we need to implement INotifyPropertyChanged for the data source class in order to trigger other radio buttons to update themselves, so that the mutual exclusivity is in effect.
Dan
Commented on 20.June 2011
Your example works to an extent, but now I am totally spooked with using RadioButton and databinding. Even with .NET 4.0, I think Microsoft still has some bugs here. If your example is used in a UserControl and more than one instance is created, it often fails to remember which radio button is supposed to be checked as the usercontrols gain and lose focus. Really strange... I'm steering clear of using this control with data binding in any form or fashion.
Dan
Commented on 21.June 2011
Your example works to an extent, but now I am totally spooked with using RadioButton and databinding. Even with .NET 4.0, I think Microsoft still has some bugs here. If your example is used in a UserControl and more than one instance is created, it often fails to remember which radio button is supposed to be checked as the usercontrols gain and lose focus. Really strange... I'm steering clear of using this control with data binding in any form or fashion.
Dan
Commented on 21.June 2011
Your example works to an extent, but now I am totally spooked with using RadioButton and databinding. Even with .NET 4.0, I think Microsoft still has some bugs here. If your example is used in a UserControl and more than one instance is created, it often fails to remember which radio button is supposed to be checked as the usercontrols gain and lose focus. Really strange... I'm steering clear of using this control with data binding in any form or fashion.
Jamie
Commented on 29.June 2011
Thank you! That was awesome :)
Shai
Commented on 18.September 2011
This is goodl example but I found a bug.
Let's say you have 3 different options in a Radio Button list. If you select option 1, then option 2, and option 3, it works. But now if you go back and select option1, your view do not communicate with ViewModel. Any suggestion on this issue?

Name
E-Mail (optional)
Comment