CheckBoxTableSourceWrapperByObject.cs 2.4 KB

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