WPF RadioButton InverseBooleanConverter 不起作用 [英] WPF RadioButton InverseBooleanConverter not working
问题描述
我有两个 RadioButton,我将它们绑定到 ViewModel 中的一个布尔属性.不幸的是,我在转换器中遇到错误,因为targetType"参数为空.
I have two RadioButtons which I am binding to a boolean property in the ViewModel. Unfortunately I am getting an error in the converter because the 'targetType' parameter is null.
现在我不期望传入的 targetType 参数为 null(我期望 True 或 False).但是我注意到 RadioButton 的 IsChecked 属性是一个可为空的布尔值,所以这种解释是这样的.
Now I wasn't expecting the targetType parameter coming through to be null (I was expecting True or False). However I noticed that the IsChecked property of the RadioButton is a nullable bool so this kind of explains it.
我可以更正 XAML 中的某些内容,还是应该更改解决方案的现有转换器?
Can I correct something in the XAML or should I be changing the solution's existing converter?
这是我的 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:
This is the existing converter I am using solution wide 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)));
}
推荐答案
您需要更改转换器,或者使用新的转换器可能更好.
You need to change the converter, or what's probably even better, use a new converter.
[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
}
这篇关于WPF RadioButton InverseBooleanConverter 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!