using System;
using System.Linq;
using System.Windows.Data;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
public class EnumDescriptionConverter<T> : EnumConverter where T : struct
{
private static Dictionary<T, string> _descriptions = new Dictionary<T, string>();
public EnumDescriptionConverter() : base(typeof(T))
{
this.Init();
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType != typeof(string))
{
return base.ConvertTo(context, culture, value, destinationType);
}
if (value == null)
{
return string.Empty;
}
if (value is T == false)
{
return value.ToString();
}
var item = (T)value;
if (_descriptions.ContainsKey(item) == false)
{
return value.ToString();
}
return _descriptions[item];
}
private void Init()
{
foreach (T item in Enum.GetValues(typeof(T)))
{
var fi = item.GetType().GetField(item.ToString());
if (fi == null)
{
_descriptions.Add(item, item.ToString());
continue;
}
var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Length < 1)
{
_descriptions.Add(item, item.ToString());
continue;
}
if (string.IsNullOrWhiteSpace(attributes[0].Description))
{
_descriptions.Add(item, item.ToString());
continue;
}
_descriptions.Add(item, attributes[0].Description);
}
}
}