我有两个 RadioButtons,我将它们绑定到 ViewModel 中的布尔属性。不幸的是,我在转换器中收到错误,因为“targetType”参数为空。
现在我并不期望 targetType 参数为空(我期望 True 或 False)。但是我注意到 RadioButton 的 IsChecked 属性是一个可为 null 的布尔值,因此可以这样解释它。
我可以更正 XAML 中的某些内容,还是应该更改解决方案的现有转换器?
这是我的 XAML:
<RadioButton Name="UseTemplateRadioButton" Content="Use Template"
GroupName="Template"
IsChecked="{Binding UseTemplate, Mode=TwoWay}" />
<RadioButton Name="CreatNewRadioButton" Content="Create New"
GroupName="Template"
IsChecked="{Binding Path=UseTemplate, Mode=TwoWay, Converter={StaticResource InverseBooleanConverter}}"/>
这是我正在使用解决方案范围的 InverseBooleanConverter 的现有转换器:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if ((targetType != typeof(bool)) && (targetType != typeof(object)))
{
throw new InvalidOperationException("The target must be a boolean");
}
return !(((value != null) && ((IConvertible)value).ToBoolean(provider)));
}
您需要更换转换器,或者使用新的转换器可能更好。
[ValueConversion(typeof(bool?), typeof(bool))]
public class Converter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (targetType != typeof(bool?))
{
throw new InvalidOperationException("The target must be a nullable boolean");
}
bool? b = (bool?)value;
return b.HasValue && b.Value;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value;
}
#endregion
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)