Add TypeConverter attribute for listing at runtime

In a C # / WPF application, I added the TypeConverter attribute for some of my enumerations to display localized text instead of enum text:

[TypeConverter(typeof(LocalizedEnumTypeConverter))] public enum MyEnum { EnumVal1 = 0, EnumVal2 = 1, EnumVal3 = 2, } 

I performed LocalizedEnumTypeConverter to accomplish this task.

The problem occurs when I try to use the same enumeration approach that is defined in another assembly that does not have access to LocalizedEnumTypeConverter and is common to other applications (that is, I cannot add a reference to the assembly where LocalizedEnumTypeConverter is defined).

Is there a way to add a TypeConverter attribute at runtime? That way, I can leave the enumeration in another assembly without the TypeConverter attribute, and then add it at runtime in my application.

+6
source share
1 answer

This can be done using the TypeDescriptor class https://msdn.microsoft.com/en-us/library/system.componentmodel.typedescriptor.aspx . Refer to the sample below.

  Attribute[] newAttributes = new Attribute[1]; newAttributes[0] = new TypeConverterAttribute(typeof(LocalizedEnumTypeConverter)); TypeDescriptor.AddAttributes(MyEnum, newAttributes); 
+7
source

Source: https://habr.com/ru/post/985261/


All Articles