EnumItemsSource.cs 1.9 KB

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