0

Can you assign a TypeConverter without a TypeConverterAttribute?

 2 years ago
source link: https://stackoverflow.com/questions/3068453/can-you-assign-a-typeconverter-without-a-typeconverterattribute
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

2 Answers

Hmm, not sure I've seen this before, but you could add the TypeConverterAttribute at runtime using a TypeDescriptor, so given my sample classes:

public class MyType
{
    public string Name;
}

public class MyTypeConverter : TypeConverter
{
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
    {
        if (sourceType == typeof(string))
            return true;

        return base.CanConvertFrom(context, sourceType);
    }

    public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
    {
        if (value.GetType() == typeof(string))
            return new MyType() { Name = (string) value };

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

I could then have a method:

public void AssignTypeConverter<IType, IConverterType>()
{
  TypeDescriptor.AddAttributes(typeof(IType), new TypeConverterAttribute(typeof(IConverterType)));
}

AssignTypeConverter<MyType, MyTypeConverter>();

Hope that helps.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK