OptionSelectorTEnum.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #nullable enable
  2. namespace Terminal.Gui.Views;
  3. /// <summary>
  4. /// Provides a user interface for displaying and selecting a single item from a list of options in a type-safe way.
  5. /// Each option is represented by a checkbox, but only one can be selected at a time.
  6. /// <see cref="OptionSelector"/> provides a non-type-safe version.
  7. /// </summary>
  8. public sealed class OptionSelector<TEnum> : OptionSelector where TEnum : struct, Enum
  9. {
  10. /// <summary>
  11. /// Initializes a new instance of the <see cref="OptionSelector{TEnum}"/> class.
  12. /// </summary>
  13. public OptionSelector ()
  14. {
  15. base.Labels = Enum.GetValues<TEnum> ().Select (f => f.ToString ()).ToArray (); ;
  16. }
  17. /// <summary>
  18. /// Gets or sets the value of the selected option.
  19. /// </summary>
  20. public new TEnum? Value
  21. {
  22. get => base.Value.HasValue ? (TEnum)Enum.ToObject (typeof (TEnum), base.Value.Value) : (TEnum?)null;
  23. set => base.Value = value.HasValue ? Convert.ToInt32 (value.Value) : null;
  24. }
  25. /// <summary>
  26. /// Prevents calling the base Values property setter with arbitrary values.
  27. /// </summary>
  28. public override IReadOnlyList<int>? Values
  29. {
  30. get => base.Values;
  31. set => throw new InvalidOperationException ("Setting Values directly is not allowed.");
  32. }
  33. /// <summary>
  34. /// Raised when <see cref="Value"/> has changed. Provides the new value as <typeparamref name="TEnum"/>?.
  35. /// </summary>
  36. public new event EventHandler<EventArgs<TEnum?>>? ValueChanged;
  37. /// <summary>
  38. /// Called when <see cref="Value"/> has changed. Raises the generic <see cref="ValueChanged"/> event.
  39. /// </summary>
  40. protected override void OnValueChanged (int? value, int? previousValue)
  41. {
  42. base.OnValueChanged (value, previousValue);
  43. TEnum? newValue = value.HasValue ? (TEnum)Enum.ToObject (typeof (TEnum), value.Value) : null;
  44. ValueChanged?.Invoke (this, new (newValue));
  45. }
  46. }