CheckGroup.cs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Windows.Forms;
  7. namespace GUI.GUIUtils
  8. {
  9. public class CheckGroup<UICheckableType> : LinkedList<WeakReference<UICheckableType>> where UICheckableType : Control, ICheckableUI
  10. {
  11. public void AddSafe(params UICheckableType[] checkable)
  12. {
  13. foreach (var it in checkable)
  14. {
  15. it.ResetClick();
  16. it.Click += (sender, _) => CheckedObject = (UICheckableType)sender;
  17. _ = AddFirst(new WeakReference<UICheckableType>(it));
  18. }
  19. }
  20. WeakReference<UICheckableType> checkedObjectReference;
  21. public UICheckableType CheckedObject
  22. {
  23. get
  24. {
  25. if (checkedObjectReference == null) return null;
  26. if (checkedObjectReference.TryGetTarget(out UICheckableType target)) return target;
  27. else checkedObjectReference = null;
  28. return null;
  29. }
  30. set
  31. {
  32. foreach (var it in this)
  33. if (it.TryGetTarget(out UICheckableType target))
  34. target.IsChecked = target == value;
  35. }
  36. }
  37. }
  38. }