I am trying to implement localized BooleanConverter. Everything works well so far, but when you double click on the property next message is being shown:
"Object of type 'System.String' cannot be converted to type 'System.Boolean'."
I suppose the problem is in method CreateInstance of TypeConverter which has that boolean property.
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);
}
}
The main problem of your code is you are overriding GetStandardValues
incorrectly.
In fact you don't need to override GetStandardValues
, just remove it and you will get expected result, that acts like original boolean converter while showing your desired strings:
When overriding GetStandardValues
you should return a list of supported values of the type that you are creating converter for, then using the ConvertTo
you provide string representation values and using ConvertFrom
, provide a way to converting the type from string values.