WPF Radio button的解决方案
WPF中的Radio button有bug,不能进行data binding.
http://geekswithblogs.net/claraoscura/archive/2008/10/17/125901.aspx
适用于boolean type的.
1. 一个converter:
/// <summary>
/// Reference:
/// http://geekswithblogs.net/claraoscura/archive/2008/10/17/125901.aspx
/// </summary>
[ValueConversion(typeof(bool), typeof(bool))]
public class RadioButtonBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
bool param = bool.Parse(parameter.ToString());
if (value == null)
{
return false;
}
else
{
return !((bool)value ^ param);
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
bool param = bool.Parse(parameter.ToString());
return !((bool)value ^ param); ;
}
2. How to use it:
(1) Add converter in resources:
<RadioButtonBooleanConverter x:Key="RadioButtonBooleanConverter" />
(2) Use converter in RadioButton:
<RadioButton GroupName="rbGroupNew"
IsChecked="{Binding Path=xxx, Mode=TwoWay, Converter={StaticResource RadioButtonBooleanConverter}, ConverterParameter=true}" Content="New" />
<RadioButton GroupName="rbGroupOld" IsChecked="{Binding Path=xxxx, Mode=TwoWay, Converter={StaticResource RadioButtonBooleanConverter}, ConverterParameter=false}" Content="Old" />
3. Essential points:
(1) xxx must be dependency property;
(2) Radio button group is different, Mode should be "TwoWay", ConverterParameter=true/false;
4. If Radio buttons states are more than one:
http://www.wpftutorial.net/RadioButton.html