WPF中的radiobox通過data binding綁定到一個bool屬性后,如下所示,盡管UI可以正確的顯示,但是data binding的屬性不能正確的更新。比如user點了No之后屬性UserChoice還是True。
<RadioButton Content="Yes" IsChecked="{Binding UserChoice}"/>
<RadioButton Content="No"/>
需要用如下的方式:
<RadioButton Content="Yes" IsChecked="{Binding UserChoice}"/>
<RadioButton Content="No" IsChecked="{Binding UserChoice, Converter={StaticResource radioConverter}}"/>
radioconverter如下:
public class RadioButtonConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is bool)
{
return !(bool)value;
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is bool)
{
return !(bool)value;
}
return value;
}
}
這樣就能正確更新了。