GUIParagraph.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Drawing;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Windows.Forms;
  8. namespace GUI.GUIUtils
  9. {
  10. public class GUIParagraph : ISizeChangedListener
  11. {
  12. // 不要长期持有WinForm控件的引用(不要长期持有拥有非托管资源和/或拥有大量托管资源的对象,为了防止环状引用,在其销毁时立即释放(一代GC))
  13. WeakReference<FlowLayoutPanel> reference;
  14. public TargetXY Target { get; set; } = TargetXY.X;
  15. public int SplitEdge { get; set; } = 10;
  16. public enum TargetXY { X, Y }
  17. public Action<Control, FlowLayoutPanel> FixedPaneReferenceFunc;
  18. public GUIParagraph(FlowLayoutPanel weak_ref)
  19. {
  20. reference = new WeakReference<FlowLayoutPanel>(weak_ref);
  21. }
  22. public void OnSizeChanged()
  23. {
  24. if (reference.TryGetTarget(out FlowLayoutPanel pane))
  25. {
  26. var selectVal = Target switch
  27. {
  28. TargetXY.X => pane.Width,
  29. TargetXY.Y => pane.Height,
  30. _ => throw new ArgumentOutOfRangeException(nameof(Target)),
  31. };
  32. int selectSize = selectVal - SplitEdge * 2;
  33. selectSize /= pane.Controls.Count;
  34. for (int i = 0; i < pane.Controls.Count; i++)
  35. {
  36. var control = pane.Controls[i];
  37. switch (Target)
  38. {
  39. case TargetXY.X:
  40. {
  41. control.Size = new Size(selectSize, control.Size.Height);
  42. control.Location = new Point(SplitEdge + i * (selectSize), control.Location.Y);
  43. }
  44. break;
  45. case TargetXY.Y:
  46. {
  47. control.Size = new Size(control.Size.Width, selectSize);
  48. control.Location = new Point(control.Location.X, SplitEdge + i * selectSize);
  49. }
  50. break;
  51. }
  52. FixedPaneReferenceFunc?.Invoke(control, pane);
  53. }
  54. }
  55. }
  56. }
  57. }