EnumItemsSource.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.ComponentModel;
  5. using System.Globalization;
  6. using System.Linq;
  7. using System.Reflection;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using System.Windows.Data;
  11. namespace DeviceCenter
  12. {
  13. public class EnumItemsSource : Dictionary<string, object>, IValueConverter
  14. {
  15. Type type;
  16. IDictionary<Object, Object> valueToNameMap;
  17. IDictionary<Object, Object> nameToValueMap;
  18. public Type Type
  19. {
  20. get { return this.type; }
  21. set
  22. {
  23. if (!value.IsEnum)
  24. throw new ArgumentException("Type is not an enum.", "value");
  25. this.type = value;
  26. Initialize();
  27. }
  28. }
  29. public Object Convert(Object value, Type targetType, Object parameter, CultureInfo culture)
  30. {
  31. return this.valueToNameMap[value];
  32. }
  33. public Object ConvertBack(Object value, Type targetType, Object parameter, CultureInfo culture)
  34. {
  35. return this.nameToValueMap[value];
  36. }
  37. void Initialize()
  38. {
  39. this.valueToNameMap = this.type
  40. .GetFields(BindingFlags.Static | BindingFlags.Public)
  41. .ToDictionary(fi => fi.GetValue(null), GetDescription);
  42. this.nameToValueMap = this.valueToNameMap
  43. .ToDictionary(kvp => kvp.Value, kvp => kvp.Key);
  44. Clear();
  45. foreach (String name in this.nameToValueMap.Keys)
  46. {
  47. this[name] = this.nameToValueMap[name];
  48. }
  49. }
  50. static Object GetDescription(FieldInfo fieldInfo)
  51. {
  52. var descriptionAttribute =
  53. (DescriptionAttribute)Attribute.GetCustomAttribute(fieldInfo, typeof(DescriptionAttribute));
  54. return descriptionAttribute != null ? descriptionAttribute.Description : fieldInfo.Name;
  55. }
  56. }
  57. }