2

我正在尝试实现本地化的 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);
    }
}
4

1 回答 1

1

您的代码的主要问题是您GetStandardValues不正确地覆盖。

事实上,您不需要覆盖GetStandardValues,只需将其删除,您就会得到预期的结果,它在显示您想要的字符串时就像原始布尔转换器一样:

在此处输入图像描述

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

于 2015-12-08T19:15:22.403 回答