EnumerationExtension.cs 1.8 KB

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