using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
namespace MyMagicEnumConverter
{
#region MyMagicEnumConverter
public class MyMagicEnumConverter<TENUM, TATTR> :
StringConverter where TATTR : MyNameBaseAttribute
{
public override bool GetStandardValuesSupported(
ITypeDescriptorContext context)
{
return true;
}
public override bool GetStandardValuesExclusive(
ITypeDescriptorContext context)
{
return true;
}
public override StandardValuesCollection GetStandardValues(
ITypeDescriptorContext context)
{
List<String> values = new List<String>();
foreach (var item in Enum.GetNames(typeof(TENUM)))
{
System.Reflection.MemberInfo[] mi = typeof(TENUM).GetMember(item);
Object[] attributes = mi[0].GetCustomAttributes(typeof(TATTR), false);
if (attributes.Length > 0)
values.Add(((TATTR)attributes[0]).Name);
else
values.Add(item);
}
return new StandardValuesCollection(values);
}
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 != null && value.GetType() == typeof(String))
{
foreach (var item in Enum.GetNames(typeof(TENUM)))
{
System.Reflection.MemberInfo[] mi = typeof(TENUM).GetMember(item);
Object[] attributes = mi[0].GetCustomAttributes(typeof(TATTR), false);
if (attributes.Length > 0)
{
if (Convert.ToString(value) == ((TATTR)attributes[0]).Name)
return Enum.Parse(typeof(TENUM), item);
}
}
return Enum.Parse(typeof(TENUM), Convert.ToString(value));
}
return base.ConvertFrom(context, culture, value);
}
public override bool CanConvertTo(ITypeDescriptorContext context,
Type destinationType)
{
if (destinationType == typeof(TENUM))
return true;
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context,
System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (value != null && value.GetType() == typeof(TENUM))
{
System.Reflection.MemberInfo[] mi =
((TENUM)value).GetType().GetMember(value.ToString());
Object[] attributes = mi[0].GetCustomAttributes(typeof(TATTR), false);
if (attributes.Length > 0)
return ((TATTR)attributes[0]).Name;
else
return Convert.ToString(value);
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
#endregion
}
MyMagicEnumConverter.zip