OptionSelectorTEnum.cs 1.9 KB

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