【问题标题】:WPF RadioButton InverseBooleanConverter not workingWPF RadioButton InverseBooleanConverter 不起作用
【发布时间】:2013-03-07 02:09:39
【问题描述】:

我有两个 RadioButton,我将它们绑定到 ViewModel 中的布尔属性。不幸的是,我在转换器中遇到错误,因为“targetType”参数为空。

现在我没想到传入的 targetType 参数为空(我期待的是 True 或 False)。但是我注意到 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)));
} 

【问题讨论】:

    标签: c# wpf radio-button ivalueconverter


    【解决方案1】:

    您需要更换转换器,或者更好的是,使用新的转换器。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-30
      • 2012-04-10
      • 2018-04-10
      • 2014-10-30
      • 2013-02-08
      • 2010-12-22
      • 2017-01-28
      • 1970-01-01
      相关资源
      最近更新 更多