2013-03-18 83 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