EnumDataProvider.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Windows.Data;
  5. namespace HandyControl.Data;
  6. public class EnumDataProvider : ObjectDataProvider
  7. {
  8. public EnumDataProvider()
  9. {
  10. MethodName = nameof(GetValues);
  11. }
  12. private Type _type;
  13. public Type Type
  14. {
  15. get => _type;
  16. set
  17. {
  18. _type = value;
  19. MethodParameters.Add(value);
  20. ObjectType = typeof(System.Enum);
  21. }
  22. }
  23. private bool _useAttributes;
  24. public bool UseAttributes
  25. {
  26. get => _useAttributes;
  27. set
  28. {
  29. _useAttributes = value;
  30. ObjectType = value ? typeof(EnumDataProvider) : typeof(System.Enum);
  31. }
  32. }
  33. public static IEnumerable<EnumItem> GetValues(Type enumType)
  34. {
  35. if (enumType == null)
  36. {
  37. throw new ArgumentNullException(nameof(enumType));
  38. }
  39. var resultList = new List<EnumItem>();
  40. var values = System.Enum.GetValues(enumType);
  41. foreach (System.Enum value in values)
  42. {
  43. var fieldInfo = enumType.GetField(value.ToString());
  44. if (fieldInfo == null)
  45. {
  46. continue;
  47. }
  48. if (fieldInfo.GetCustomAttributes(typeof(BrowsableAttribute), true) is BrowsableAttribute[] { Length: > 0 } browsableAttributes)
  49. {
  50. if (!browsableAttributes[0].Browsable)
  51. {
  52. continue;
  53. }
  54. }
  55. if (fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), true) is DescriptionAttribute[] { Length: > 0 } descriptionAttributes)
  56. {
  57. resultList.Add(new EnumItem
  58. {
  59. Description = descriptionAttributes[0].Description,
  60. Value = value
  61. });
  62. }
  63. }
  64. return resultList;
  65. }
  66. }