Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

68 rindas
2.0 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. //枚举字段
  17. private Type _enumType;
  18. public Type EnumType
  19. {
  20. get => _enumType;
  21. set
  22. {
  23. if (value != _enumType)
  24. {
  25. if (value != null)
  26. {
  27. Type enumType = Nullable.GetUnderlyingType(value) ?? value;
  28. if (!enumType.IsEnum)
  29. throw new ArgumentException("Type must be for an Enum.");
  30. }
  31. _enumType = value;
  32. }
  33. }
  34. }
  35. public EnumBindingSourceExtension() { }
  36. public EnumBindingSourceExtension(Type enumType)
  37. {
  38. EnumType = enumType;
  39. }
  40. /// <summary>
  41. /// 将枚举转换为数组,返回出去
  42. /// 可以绑定可空枚举
  43. /// </summary>
  44. /// <param name="serviceProvider">xmal上下文</param>
  45. /// <returns></returns>
  46. /// <exception cref="InvalidOperationException"></exception>
  47. public override object ProvideValue(IServiceProvider serviceProvider)
  48. {
  49. if (_enumType == null)
  50. throw new InvalidOperationException("The EnumType must be specified.");
  51. var actualEnumType = Nullable.GetUnderlyingType(_enumType) ?? _enumType;
  52. var enumValues = Enum.GetValues(actualEnumType);
  53. if (actualEnumType == _enumType)
  54. return enumValues;
  55. var tempArray = Array.CreateInstance(actualEnumType, enumValues.Length + 1);
  56. enumValues.CopyTo(tempArray, 1);
  57. return tempArray;
  58. }
  59. }
  60. }