自定义本地化 BooleanConverter

Custom localized BooleanConverter

我正在尝试实现本地化的 BooleanConverter。到目前为止一切正常,但是当您 双击 属性 时,将显示下一条消息:

"Object of type 'System.String' cannot be converted to type '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);
    }
}

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

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

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