You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

51 lines
1.5 KiB

  1. using System;
  2. using System.ComponentModel;
  3. using System.Globalization;
  4. namespace BPA.UIControl.Commons
  5. {
  6. /// <summary>
  7. /// Enum -> Description
  8. /// </summary>
  9. public class EnumDescriptionConverter : EnumConverter
  10. {
  11. /// <summary>
  12. /// Initializes a new instance of the <see cref="EnumDescriptionConverter"/> class.
  13. /// </summary>
  14. /// <param name="type">The type.</param>
  15. public EnumDescriptionConverter(Type type)
  16. : base(type)
  17. {
  18. }
  19. /// <inheritdoc/>
  20. public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
  21. {
  22. if (destinationType == typeof(string))
  23. {
  24. return value?.GetDescription();
  25. }
  26. return string.Empty;
  27. }
  28. /// <inheritdoc/>
  29. public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
  30. {
  31. if (value is string)
  32. {
  33. var enumValues = EnumType.GetEnumValues();
  34. for (int i = 0; i < enumValues.Length; i++)
  35. {
  36. var enumValue = enumValues.GetValue(i);
  37. if (value.Equals(enumValue.GetDescription()))
  38. {
  39. return enumValue;
  40. }
  41. }
  42. }
  43. return base.ConvertFrom(context, culture, value);
  44. }
  45. }
  46. }