using DTS.Common.SharedResource.Strings; using System; using System.ComponentModel; using System.Linq; namespace DTS.Common.Converters { /// /// Display enum description instead of enum value /// http://brianlagunas.com/a-better-way-to-data-bind-enums-in-wpf/ /// public class EnumDescriptionTypeConverterShared : EnumConverter { public EnumDescriptionTypeConverterShared(Type type) : base(type) { } /// /// Modifies the source data before passing it to the target for display in the UI. /// /// The value to be converted /// The source data being passed to the target. /// The culture of the conversion. /// The System.Type of data expected by the target dependency property. /// The value to be passed to the target dependency property. 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; var fi = value.GetType().GetField(value.ToString()); if (fi == null) return string.Empty; var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false); if (!attributes.Any() || string.IsNullOrEmpty(attributes[0].Description)) return value.ToString(); var s = StringResources.ResourceManager.GetString(attributes[0].Description); return string.IsNullOrWhiteSpace(s) ? attributes[0].Description : s; } public static string GetEnumDescription(Enum value) { var fi = value.GetType().GetField(value.ToString()); DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes (typeof(DescriptionAttribute), false); if (attributes.Length > 0) { var s = StringResources.ResourceManager.GetString(attributes[0].Description); if (!string.IsNullOrWhiteSpace(s)) { return s; } return attributes[0].Description; } return value.ToString(); } } }