问题
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.
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.
Can I correct something in the XAML or should I be changing the solution's existing converter?
Here's my 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}}"/>
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)));
}
回答1:
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
}
来源:https://stackoverflow.com/questions/15481916/wpf-radiobutton-inversebooleanconverter-not-working