CheckBoxTableSourceWrapperByObject.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 <see cref="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. }
  69. }