EnumDescriptionConverter.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. using System;
  2. using System.ComponentModel;
  3. using System.Globalization;
  4. using System.Reflection;
  5. using System.Windows.Data;
  6. namespace TeamAAS.Converters
  7. {
  8. public class EnumDescriptionConverter : IValueConverter
  9. {
  10. public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  11. {
  12. if (value == null) return null;
  13. var type = value.GetType();
  14. if (!type.IsEnum) return value;
  15. var field = type.GetField(value.ToString());
  16. if (field == null) return value;
  17. var attr = field.GetCustomAttribute<DescriptionAttribute>();
  18. return attr?.Description ?? value.ToString();
  19. }
  20. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  21. {
  22. if (value == null) return Binding.DoNothing;
  23. if (!targetType.IsEnum) return Binding.DoNothing;
  24. foreach (var field in targetType.GetFields(BindingFlags.Public | BindingFlags.Static))
  25. {
  26. var attr = field.GetCustomAttribute<DescriptionAttribute>();
  27. if (attr != null && attr.Description == value.ToString())
  28. return field.GetValue(null);
  29. }
  30. try { return Enum.Parse(targetType, value.ToString()); }
  31. catch { return Binding.DoNothing; }
  32. }
  33. }
  34. }