2 using System.Collections.Generic;
3 using System.Collections.ObjectModel;
5 namespace Tizen.NUI.Binding
7 internal class AttachedCollection<T> : ObservableCollection<T>, ICollection<T>, IAttachedObject where T : BindableObject, IAttachedObject
9 readonly List<WeakReference> _associatedObjects = new List<WeakReference>();
11 public AttachedCollection()
15 public AttachedCollection(IEnumerable<T> collection) : base(collection)
19 public AttachedCollection(IList<T> list) : base(list)
23 public void AttachTo(BindableObject bindable)
26 throw new ArgumentNullException("bindable");
27 OnAttachedTo(bindable);
30 public void DetachFrom(BindableObject bindable)
32 OnDetachingFrom(bindable);
35 protected override void ClearItems()
37 foreach (WeakReference weakbindable in _associatedObjects)
39 foreach (T item in this)
41 var bindable = weakbindable.Target as BindableObject;
44 item?.DetachFrom(bindable);
50 protected override void InsertItem(int index, T item)
52 base.InsertItem(index, item);
53 foreach (WeakReference weakbindable in _associatedObjects)
55 var bindable = weakbindable.Target as BindableObject;
58 item?.AttachTo(bindable);
62 protected virtual void OnAttachedTo(BindableObject bindable)
64 lock (_associatedObjects)
66 _associatedObjects.Add(new WeakReference(bindable));
68 foreach (T item in this)
69 item?.AttachTo(bindable);
72 protected virtual void OnDetachingFrom(BindableObject bindable)
74 foreach (T item in this)
75 item?.DetachFrom(bindable);
76 lock (_associatedObjects)
78 for (var i = 0; i < _associatedObjects.Count; i++)
80 object target = _associatedObjects[i].Target;
82 if (target == null || target == bindable)
84 _associatedObjects.RemoveAt(i);
91 protected override void RemoveItem(int index)
94 foreach (WeakReference weakbindable in _associatedObjects)
96 var bindable = weakbindable.Target as BindableObject;
99 item?.DetachFrom(bindable);
102 base.RemoveItem(index);
105 protected override void SetItem(int index, T item)
108 foreach (WeakReference weakbindable in _associatedObjects)
110 var bindable = weakbindable.Target as BindableObject;
111 if (bindable == null)
113 old?.DetachFrom(bindable);
116 base.SetItem(index, item);
118 foreach (WeakReference weakbindable in _associatedObjects)
120 var bindable = weakbindable.Target as BindableObject;
121 if (bindable == null)
123 item?.AttachTo(bindable);