EnumBindingSourceExtension.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using System;
  2. using System.ComponentModel;
  3. using System.Linq;
  4. using System.Windows.Markup;
  5. using InABox.Core;
  6. namespace InABox.WPF;
  7. public class EnumFormatterExtension : MarkupExtension
  8. {
  9. private readonly Type _type;
  10. public EnumFormatterExtension(Type type)
  11. {
  12. _type = type;
  13. }
  14. public override object ProvideValue(IServiceProvider serviceProvider)
  15. {
  16. return Enum.GetValues(_type)
  17. .Cast<object>()
  18. .Select(e => new { Value = (int)e, DisplayName = $"{e}".SplitCamelCase() });
  19. }
  20. }
  21. public class EnumToStringConverter : AbstractConverter<object?,string>
  22. {
  23. private string GetDescription(Type enumType, object? enumValue)
  24. {
  25. if (enumValue == null)
  26. return string.Empty;
  27. return
  28. enumType
  29. .GetField($"{enumValue}")?
  30. .GetCustomAttributes(typeof(DescriptionAttribute), false)
  31. .FirstOrDefault() is DescriptionAttribute _descriptionAttribute
  32. ? _descriptionAttribute.Description
  33. : $"{enumValue}".SplitCamelCase() ?? "";
  34. }
  35. public override string Convert(object? value)
  36. {
  37. if (value == null)
  38. return String.Empty;
  39. Type _type = value.GetType();
  40. return
  41. _type.IsEnum
  42. ? GetDescription(_type, value)
  43. : String.Empty;
  44. }
  45. }