Introduction
TheRadioButton
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 theIsChecked
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; } }
No comments:
Post a Comment