You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

57 rivejä
1.6 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. class EnumBindingSourceExtension : MarkupExtension
  10. {
  11. private Type _enumType;
  12. public Type EnumType
  13. {
  14. get => _enumType;
  15. set
  16. {
  17. if (value != _enumType)
  18. {
  19. if (value != null)
  20. {
  21. Type enumType = Nullable.GetUnderlyingType(value) ?? value;
  22. if (!enumType.IsEnum)
  23. throw new ArgumentException("Type must be for an Enum.");
  24. }
  25. _enumType = value;
  26. }
  27. }
  28. }
  29. public EnumBindingSourceExtension() { }
  30. public EnumBindingSourceExtension(Type enumType)
  31. {
  32. EnumType = enumType;
  33. }
  34. public override object ProvideValue(IServiceProvider serviceProvider)
  35. {
  36. if (_enumType == null)
  37. throw new InvalidOperationException("The EnumType must be specified.");
  38. var actualEnumType = Nullable.GetUnderlyingType(_enumType) ?? _enumType;
  39. var enumValues = Enum.GetValues(actualEnumType);
  40. if (actualEnumType == _enumType)
  41. return enumValues;
  42. var tempArray = Array.CreateInstance(actualEnumType, enumValues.Length + 1);
  43. enumValues.CopyTo(tempArray, 1);
  44. return tempArray;
  45. }
  46. }
  47. }