2013-03-18 88 views
3

我有两个RadioButtons,我绑定到ViewModel中的布尔属性。不幸的是我在转换器中出现错误,因为'targetType'参数为空。WPF RadioButton InverseBooleanConverter不工作

现在我没想到的目标类型的参数来通过为空(我所期待的真或假)。但是我注意到RadioButton的IsChecked属性是一个可空的布尔,所以这种解释。

我可以纠正一些在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))); 
} 

回答

3

您需要更改转换器,或者什么可能是更好的,使用新转换器。

[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 
} 
+1

编辑:添加完整的类代码。 – Shlomo 2013-03-18 17:42:19