1

我想实现本地化的BooleanConverter。目前为止一切正常,但当你双击属性下一条消息正在显示:自定义本地化BooleanConverter

“对象的类型'System.String'不能转换为'System.Boolean'类型。

我想问题是在具有该布尔属性的TypeConverter的CreateInstance方法中。

public class BoolTypeConverter : BooleanConverter 
{ 
    private readonly string[] values = { Resources.BoolTypeConverter_False, Resources.BoolTypeConverter_True }; 

    public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) 
    { 
     if (destinationType == typeof(string) && value != null) 
     { 
      var valueType = value.GetType(); 

      if (valueType == typeof(bool)) 
      { 
       return values[(bool)value ? 1 : 0]; 
      } 
      else if (valueType == typeof(string)) 
      { 
       return value; 
      } 
     } 

     return base.ConvertTo(context, culture, value, destinationType); 
    } 

    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) 
    { 
     var stringValue = value as string; 

     if (stringValue != null) 
     { 
      if (values[0] == stringValue) 
      { 
       return true; 
      } 
      if (values[1] == stringValue) 
      { 
       return false; 
      } 
     } 

     return base.ConvertFrom(context, culture, value); 
    } 

    public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) 
    { 
     return new StandardValuesCollection(values); 
    } 
} 

回答

1

你的代码的主要问题是你错误地覆盖了GetStandardValues

其实你并不需要重写GetStandardValues,只是删除它,你会得到预期的结果,就像原来的布尔转换器,同时显示您所需的字符串:当重写GetStandardValues

enter image description here

应返回您正在创建转换器的类型的支持值列表,然后使用提供字符串表示值的ConvertTo并使用ConvertFrom提供一种将字符串值转换为类型的方法。

相关问题