EnumerationExtension.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Windows.Markup;
  8. namespace ConfigureWindow
  9. {
  10. public class EnumerationExtension : MarkupExtension
  11. {
  12. private Type _enumType;
  13. public EnumerationExtension(Type enumType)
  14. {
  15. if (enumType == null)
  16. throw new ArgumentNullException("enumType");
  17. EnumType = enumType;
  18. }
  19. public Type EnumType
  20. {
  21. get { return _enumType; }
  22. private set
  23. {
  24. if (_enumType == value)
  25. return;
  26. var enumType = Nullable.GetUnderlyingType(value) ?? value;
  27. if (enumType.IsEnum == false)
  28. throw new ArgumentException("Type must be an Enum.");
  29. _enumType = value;
  30. }
  31. }
  32. public override object ProvideValue(IServiceProvider serviceProvider)
  33. {
  34. var enumValues = Enum.GetValues(EnumType);
  35. return (
  36. from object enumValue in enumValues
  37. select new EnumerationMember
  38. {
  39. Value = enumValue,
  40. Description = GetDescription(enumValue)
  41. }).ToArray();
  42. }
  43. private string GetDescription(object enumValue)
  44. {
  45. var descriptionAttribute = EnumType
  46. .GetField(enumValue.ToString())
  47. .GetCustomAttributes(typeof(DescriptionAttribute), false)
  48. .FirstOrDefault() as DescriptionAttribute;
  49. return descriptionAttribute != null
  50. ? descriptionAttribute.Description
  51. : enumValue.ToString();
  52. }
  53. public class EnumerationMember
  54. {
  55. public string Description { get; set; }
  56. public object Value { get; set; }
  57. }
  58. }
  59. }