LightModelConverter.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Linq;
  5. using TeamAAS.Communication.LightSources;
  6. namespace Plugins.Standard.Core
  7. {
  8. public class LightModelConverter : StringConverter
  9. {
  10. public override bool GetStandardValuesSupported(ITypeDescriptorContext context) => true;
  11. public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
  12. {
  13. var values = new List<string>();
  14. foreach (LightModel model in Enum.GetValues(typeof(LightModel)))
  15. {
  16. var field = typeof(LightModel).GetField(model.ToString());
  17. var attr = field?.GetCustomAttributes(typeof(DescriptionAttribute), false)
  18. .OfType<DescriptionAttribute>()
  19. .FirstOrDefault();
  20. values.Add(attr?.Description ?? model.ToString());
  21. }
  22. return new StandardValuesCollection(values);
  23. }
  24. public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) =>
  25. sourceType == typeof(string) || sourceType == typeof(LightModel);
  26. public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
  27. {
  28. if (value is LightModel lm) return lm;
  29. if (value is string str)
  30. {
  31. foreach (LightModel model in Enum.GetValues(typeof(LightModel)))
  32. {
  33. var field = typeof(LightModel).GetField(model.ToString());
  34. var attr = field?.GetCustomAttributes(typeof(DescriptionAttribute), false)
  35. .OfType<DescriptionAttribute>()
  36. .FirstOrDefault();
  37. if (attr?.Description == str || model.ToString() == str)
  38. return model;
  39. }
  40. }
  41. return LightModel.KCS_KDC_12V60W_4T;
  42. }
  43. public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) =>
  44. destinationType == typeof(string) || destinationType == typeof(LightModel);
  45. public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
  46. {
  47. if (destinationType == typeof(LightModel) && value is string str)
  48. return ConvertFrom(context, culture, str);
  49. if (destinationType == typeof(string) && value is LightModel model)
  50. {
  51. var field = typeof(LightModel).GetField(model.ToString());
  52. var attr = field?.GetCustomAttributes(typeof(DescriptionAttribute), false)
  53. .OfType<DescriptionAttribute>()
  54. .FirstOrDefault();
  55. return attr?.Description ?? model.ToString();
  56. }
  57. return value;
  58. }
  59. }
  60. }