我有以下的單選按鈕綁定到變量IsAllowed
綁定到一個單選按鈕
<RadioButton Name="YesRadioButton" Margin="5,5,0,0" IsChecked="{Binding Path=IsAllowed, Mode=TwoWay}">Yes</RadioButton>
我怎樣才能讓否按鈕採取相反的價值只能用XAML?
我有以下的單選按鈕綁定到變量IsAllowed
綁定到一個單選按鈕
<RadioButton Name="YesRadioButton" Margin="5,5,0,0" IsChecked="{Binding Path=IsAllowed, Mode=TwoWay}">Yes</RadioButton>
我怎樣才能讓否按鈕採取相反的價值只能用XAML?
沒有Xaml專用解決方案。儘管如此,您可以使用反向布爾轉換器綁定「否」。
<local:NotConverter x:Key="notConverter"/>
{Binding IsAllowed, Mode=TwoWay, Converter=notConverter}
public class NotConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
Boolean result = false;
if (value is Boolean)
result = !((Boolean)value);
return result;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
Boolean result = false;
if (value is Boolean)
result = !((Boolean)value);
return result;
}
}
您必須使用IValueConverter來編寫轉換器。這裏是一個例子如何去做WPF - Bind to Opposite Boolean Value Using a Converter
你不需要。它會默認發生。
只要確保IsAllowed
以true
開頭,剩下的就會照顧好自己。
這是因爲當你點擊No
按鈕,它會自動設置Yes
按鈕的檢查值(這是單選按鈕的工作原理),所以此更改會自動發生,你支持類將被更新。
甚至更好:只需使用複選框即可。是/否情況是他們設計的。
上述答案的工作原理,但我想要一個轉換器,將適用於是和無單選按鈕,並反映可空布爾值的值。所以我提出,需要的變頻器參數的優勢替代:
public class YesNoRadioButtonToBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return CompareValueWithRequiredValueToBeChecked(value, parameter);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return CompareValueWithRequiredValueToBeChecked(value, parameter);
}
private bool CompareValueWithRequiredValueToBeChecked(object value, object parameterValue)
{
bool? convertedValue = ConvertObjectToBool(value);
bool? convertedParameter = ConvertObjectToBool(parameterValue);
bool result = convertedValue == convertedParameter;
return result;
}
private bool? ConvertObjectToBool(object parameter)
{
string stringResult = parameter == null ? null : parameter.ToString();
bool? convertedResult;
bool convertResultTest = false;
if (stringResult != null && !bool.TryParse(stringResult, out convertResultTest))
{
throw new InvalidCastException(string.Format("Cannot convert {0} to a bool.", parameter));
}
convertedResult = stringResult == null ? (bool?)null : (bool?)convertResultTest;
return convertedResult;
}
}
這裏是什麼XAML的樣子:
<converters:YesNoRadioButtonToBooleanConverter x:Key="yesNoToBool" />
<RadioButton Content="Yes" Name="radYes" GroupName="Group1" IsChecked="{Binding Path=boolProperty1, Mode=TwoWay, Converter={StaticResource yesNoToBool}, ConverterParameter=true}" />
<RadioButton Content="No" Name="radNo" GroupName="Group1" IsChecked="{Binding Path=boolProperty1, Mode=TwoWay, Converter={StaticResource yesNoToBool}, ConverterParameter=false}" />
,我怎麼綁定到無按鈕? – kaycee
{綁定允許,模式=雙向,轉換器= notConverter} –