Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

60 righe
1.7 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Windows.Markup;
  7. namespace ModbusDemo.Extension
  8. {
  9. /// <summary>
  10. /// 此处代码是复制粘贴,用来让枚举类型绑定到下拉框上
  11. /// </summary>
  12. class EnumBindingSourceExtension : MarkupExtension
  13. {
  14. private Type _enumType;
  15. public Type EnumType
  16. {
  17. get => _enumType;
  18. set
  19. {
  20. if (value != _enumType)
  21. {
  22. if (value != null)
  23. {
  24. Type enumType = Nullable.GetUnderlyingType(value) ?? value;
  25. if (!enumType.IsEnum)
  26. throw new ArgumentException("Type must be for an Enum.");
  27. }
  28. _enumType = value;
  29. }
  30. }
  31. }
  32. public EnumBindingSourceExtension() { }
  33. public EnumBindingSourceExtension(Type enumType)
  34. {
  35. EnumType = enumType;
  36. }
  37. public override object ProvideValue(IServiceProvider serviceProvider)
  38. {
  39. if (_enumType == null)
  40. throw new InvalidOperationException("The EnumType must be specified.");
  41. var actualEnumType = Nullable.GetUnderlyingType(_enumType) ?? _enumType;
  42. var enumValues = Enum.GetValues(actualEnumType);
  43. if (actualEnumType == _enumType)
  44. return enumValues;
  45. var tempArray = Array.CreateInstance(actualEnumType, enumValues.Length + 1);
  46. enumValues.CopyTo(tempArray, 1);
  47. return tempArray;
  48. }
  49. }
  50. }