CheckBoxTableSourceWrapperByObject.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #nullable disable
  2. namespace Terminal.Gui.Views;
  3. /// <summary>
  4. /// Implementation of <see cref="CheckBoxTableSourceWrapperBase"/> which records toggled rows by a property on row
  5. /// objects.
  6. /// </summary>
  7. public class CheckBoxTableSourceWrapperByObject<T> : CheckBoxTableSourceWrapperBase
  8. {
  9. private readonly Func<T, bool> _getter;
  10. private readonly Action<T, bool> _setter;
  11. private readonly IEnumerableTableSource<T> _toWrap;
  12. /// <summary>Creates a new instance of the class wrapping the collection <paramref name="toWrap"/>.</summary>
  13. /// <param name="tableView">The table you will use the source with.</param>
  14. /// <param name="toWrap">The collection of objects you will record checked state for</param>
  15. /// <param name="getter">Delegate method for retrieving checked state from your objects of type <typeparamref name="T"/>.</param>
  16. /// <param name="setter">Delegate method for setting new checked states on your objects of type <typeparamref name="T"/>.</param>
  17. public CheckBoxTableSourceWrapperByObject (
  18. TableView tableView,
  19. IEnumerableTableSource<T> toWrap,
  20. Func<T, bool> getter,
  21. Action<T, bool> setter
  22. ) : base (tableView, toWrap)
  23. {
  24. _toWrap = toWrap;
  25. _getter = getter;
  26. _setter = setter;
  27. }
  28. /// <inheritdoc/>
  29. protected override void ClearAllToggles ()
  30. {
  31. foreach (T e in _toWrap.GetAllObjects ())
  32. {
  33. _setter (e, false);
  34. }
  35. }
  36. /// <inheritdoc/>
  37. protected override bool IsChecked (int row) { return _getter (_toWrap.GetObjectOnRow (row)); }
  38. /// <inheritdoc/>
  39. protected override void ToggleAllRows () { ToggleRows (Enumerable.Range (0, _toWrap.Rows).ToArray ()); }
  40. /// <inheritdoc/>
  41. protected override void ToggleRow (int row)
  42. {
  43. T d = _toWrap.GetObjectOnRow (row);
  44. _setter (d, !_getter (d));
  45. }
  46. /// <inheritdoc/>
  47. protected override void ToggleRows (int [] range)
  48. {
  49. // if all are ticked untick them
  50. if (range.All (IsChecked))
  51. {
  52. // select none
  53. foreach (int r in range)
  54. {
  55. _setter (_toWrap.GetObjectOnRow (r), false);
  56. }
  57. }
  58. else
  59. {
  60. // otherwise tick all
  61. foreach (int r in range)
  62. {
  63. _setter (_toWrap.GetObjectOnRow (r), true);
  64. }
  65. }
  66. }
  67. }