Control.ControlCollection.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. namespace System.Windows.Forms
  4. {
  5. public partial class Control
  6. {
  7. public class ControlCollection : CollectionBase
  8. {
  9. private Control owner;
  10. public Control this[int index] => (Control)List[index];
  11. public int Add(Control control)
  12. {
  13. int index = IndexOf(control);
  14. if (index != -1)
  15. return index;
  16. if (control.Parent != null)
  17. control.Parent = null;
  18. var result = List.Add(control);
  19. owner.AddChild(control);
  20. control.SetParent(owner);
  21. if (control.Dock != DockStyle.None)
  22. owner.UpdateLayout();
  23. owner.DoControlAdded(control);
  24. return result;
  25. }
  26. public void AddRange(Control[] controls)
  27. {
  28. foreach (Control c in controls)
  29. Add(c);
  30. }
  31. public void Remove(Control control)
  32. {
  33. List.Remove(control);
  34. owner.RemoveChild(control);
  35. control.SetParent(null);
  36. if (control.Dock != DockStyle.None)
  37. owner.UpdateLayout();
  38. owner.DoControlRemoved(control);
  39. }
  40. public new void RemoveAt(int index) => Remove(this[index]);
  41. public new void Clear()
  42. {
  43. while (Count > 0)
  44. Remove(this[0]);
  45. }
  46. public int IndexOf(Control control) => List.IndexOf(control);
  47. public bool Contains(Control control) => List.Contains(control);
  48. public void SetChildIndex(Control control, int index)
  49. {
  50. List.Remove(control);
  51. List.Insert(index, control);
  52. owner.RemoveChild(control);
  53. owner.SetChildIndex(control, index);
  54. control.SetParent(owner);
  55. if (control.Dock != DockStyle.None)
  56. owner.UpdateLayout();
  57. }
  58. public void Insert(int index, Control control)
  59. {
  60. Add(control);
  61. SetChildIndex(control, index);
  62. }
  63. private void Find(string name, bool searchChildren, List<Control> result)
  64. {
  65. foreach (Control c in List)
  66. {
  67. if (c.Name == name)
  68. result.Add(c);
  69. if (searchChildren)
  70. c.Controls.Find(name, searchChildren, result);
  71. }
  72. }
  73. public Control[] Find(string name, bool searchChildren)
  74. {
  75. List<Control> result = new List<Control>();
  76. Find(name, searchChildren, result);
  77. return result.ToArray();
  78. }
  79. public ControlCollection(Control owner)
  80. {
  81. this.owner = owner;
  82. }
  83. }
  84. }
  85. }