Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

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