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
Mohd. Irshad
Commented on 30.April 2009
m confuse can u explain this in detail...
sanket
Commented on 4.May 2009
pls. explain this by giving examples in a step wise manner.
Sujith
Commented on 5.May 2009
plz, explain in detail or put comments on the code
sreeram
Commented on 30.May 2009
i too confused with this concept "DataBind Radio Buttons in WPF"
i am not able to do practically
savi
Commented on 11.June 2009
Not clear... confusing
Muneer
Commented on 25.June 2009
Explain Diffrence Between Windows radio Button and Wpf Radio Button
Priyaranjan
Commented on 29.June 2009
This is very complex.Not so clear
Sumit
Commented on 12.July 2009
WPF Data Binding with RadioButton :
http://blogs.msdn.com/mthalman/archive/2008/09/04/wpf-data-binding-with-radiobutton.aspx

anu
Commented on 15.July 2009
not understanding anything.getting confused.please write in detail
Pablo
Commented on 9.August 2009
I'm almost 3 hours trying to understand why this is so much complex! I guess so Microsoft is joking us with this peace of shit of WPF!!
Pepe
Commented on 10.August 2009
La verdad, no entiendo porque nos hacen la vida tan dificil si antiguamente lo solucionabas con un radioButton.Checked y listo!

Matt
Commented on 3.September 2009
Useless tutorial. At least explain what you trying to do
Jack
Commented on 11.September 2009
Suppose I believe most of you here have never used a radio button in the programming world.

The article explains it very clearly. when you select an item from the group of option, previously selected item will get unselected. These are done by number of events created and handled in the background by the windown event handle.

one of the event is clear all selected items, this event called before selecting the new item event.

When databinding if you are not careful you will most likely to get cought up in the clear all event eating the next event that is select new item from the group.

If you are not familier with mush lower level windows programming or doesn't have an experience of using database in windows application, don't bother with databinding, just deselect and select items manually.
Xiaohong
Commented on 29.September 2009
Awefull! This is not a tutorial. It is a puzzle! I spent a lot of time to make it work.
Hoang
Commented on 16.October 2009
thank you for everything
Hoang
Commented on 16.October 2009
how to make up for Radiobutton
Ivanauskas
Commented on 19.October 2009
I understood nothing.
Robert
Commented on 28.October 2009
I think most of the confusion here stems out of the Converter, and the fact that the example here is incomplete.

First, it requires you to know a little on data binding - how and why you want to do it, and to already have attempted to DataBind using the "Conventional" way - the latter part of the tutorial describes a much more advanced workaround to an internal issue in WPF.

It also requires that you have something in your code to bind against (In this case, there assumes that you have something called "CurrentOption" as a string.

The Binding Path means that it takes this string, and passes it through the EnumMatchToBooleanConverter class. The reason that this needs to be done is that IsChecked is a bool.
The ConverterParameter gives an extra parameter to match against.

The Mode on the Binding means that it goes in two directions, using the ConvertBack method.

What happens, in essence, is that checking a radio button changes the CurrentOption, which in turn causes the (otherwise unrelated) other radio buttons to be updated.
Harry
Commented on 18.November 2009
Interesting that so many people complain that they can't figure out what is going on in this tutorial. Let them go figure it out themselves then. Why do they expect everything to be just handed to them?
ALe
Commented on 30.December 2009
Very good post - if they don't understand it, bad for them.
It is very clear.

Thanks.
A
Commented on 31.December 2009
Hi geniuses, i got this error. I have a radiobutton.xaml, i pasted the whole class in radiobutton.xaml.cs, but when i compiled, i get this:
Error 2 The type 'EnumMatchToBooleanConverter' was not found. Verify that you are not missing an assembly reference and that all referenced assemblies have been built. radiobutton.xaml 6 10 WPFTest

any comments?
A
Commented on 31.December 2009
Hi geniuses, i got this error. I have a radiobutton.xaml, i pasted the whole class in radiobutton.xaml.cs, but when i compiled, i get this:
Error 2 The type 'EnumMatchToBooleanConverter' was not found. Verify that you are not missing an assembly reference and that all referenced assemblies have been built. radiobutton.xaml 6 10 WPFTest

any comments?
A
Commented on 31.December 2009
sorry to have posted twice. ok ok, my bad, i didn't include
xmlns:c="clr-namespace:WPFTest"
Jaydev
Commented on 4.January 2010
How to place multuple other controls in Groupbox in combined group
su
Commented on 5.January 2010
Thanks, Jack & Robert for clarifying. :)
MasterShake
Commented on 21.January 2010
Amazing how everyone wants everything for free. If you don't understand what is going on here - there are plenty of books available for purchase. But no, tell me now what I want dammit!!!!
Adam
Commented on 2.February 2010
This isn't clear if you're new to WPF. If you understand something about data binding and value converters, this is certainly clear. However, the GroupName should be the same on all the radio buttons.
Hoa Nguyen
Commented on 3.February 2010
It's usefule. It works for me.
Great thanks
Monir Sabbagh
Commented on 4.February 2010
It is confusing bcz there is a well-known issue with WPF RadioButton controls with data binding (when a radio button is unchecked the data binding is not undone). There are several solutions to this issue, this blog explains a good one, so it put each radio button in a different group and link their checked/unchecked values via the converter.
Monir Sabbagh
Commented on 4.February 2010
It is confusing bcz there is a well-known issue with WPF RadioButton controls with data binding (when a radio button is unchecked the data binding is not undone). There are several solutions to this issue, this blog explains a good one, so it put each radio button in a different group and link their checked/unchecked values via the converter.
Avelino
Commented on 20.February 2010
Thanks Christian. It seemed a little bit confusing to me at the beginning, but finally I understood. Very useful information.
In certain way I agree with pepe. :-)
Ashar
Commented on 22.February 2010
Thanks Christian.

This is indeed a very helpful post. The radio button group names are differnt since there seems to be a "bug" in WPF due to which when the value of the enum to which our radio buttons are bound is changed from the code the radio buttons seem to loose their binding. But when you change the group names then the binding seems to hold perfectly.

Hope MS will take care of this in next version of WPF.
Vlady
Commented on 8.March 2010
Great sample, works fine !
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