CheckBoxTableSourceWrapperByObject.cs 2.1 KB

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