CheckedListBox.ObjectCollection.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using System.Collections;
  2. namespace System.Windows.Forms
  3. {
  4. public partial class CheckedListBox
  5. {
  6. public new class ObjectCollection : CollectionBase
  7. {
  8. private CheckedListBox owner { get; }
  9. private IList items { get; }
  10. public object this[int index] => ((Item)items[index])?.Value;
  11. public new int Count => items.Count;
  12. public void Add(object obj, CheckState check)
  13. {
  14. var item = new Item(owner, obj);
  15. items.Add(item);
  16. item.SetState(check);
  17. owner.ClearCheckedItems();
  18. }
  19. public void Add(object obj, bool isChecked) => Add(obj, isChecked ? CheckState.Checked : CheckState.Unchecked);
  20. public void Add(object obj) => Add(obj, false);
  21. public void AddRange(object[] objects)
  22. {
  23. foreach (object obj in objects)
  24. Add(obj);
  25. }
  26. public void Insert(int index, object obj)
  27. {
  28. var item = new Item(owner, obj);
  29. items.Insert(index, item);
  30. item.SetState(CheckState.Unchecked);
  31. owner.ClearCheckedItems();
  32. }
  33. public void Remove(object obj)
  34. {
  35. int index = IndexOf(obj);
  36. if (index != -1)
  37. RemoveAt(index);
  38. }
  39. public new void RemoveAt(int index)
  40. {
  41. items.RemoveAt(index);
  42. owner.ClearCheckedItems();
  43. }
  44. public new void Clear()
  45. {
  46. items.Clear();
  47. owner.ClearCheckedItems();
  48. }
  49. public int IndexOf(object obj)
  50. {
  51. for (int i = 0; i < Count; i++)
  52. {
  53. if (this[i] == obj)
  54. return i;
  55. }
  56. return -1;
  57. }
  58. public bool Contains(object obj) => IndexOf(obj) != -1;
  59. internal int IndexOfItem(object item) => items.IndexOf(item);
  60. // the reason for this method is that enumerator must return Item.Value rather than Item itself
  61. public new IEnumerator GetEnumerator()
  62. {
  63. foreach (Item item in items)
  64. yield return item.Value;
  65. }
  66. internal ObjectCollection(CheckedListBox owner, IList items)
  67. {
  68. this.owner = owner;
  69. this.items = items;
  70. }
  71. }
  72. }
  73. }