How to have Lists with events upon change in List

12,956

You can use ObservableCollection and you can extend it !!
Namespace: System.Collections.ObjectModel
Assembly: WindowsBase (in WindowsBase.dll)

This collection fires events whenever the list is changed.(say any items are added, removed from list)

But note : The ObservableCollection doesnt fire events if the internal properties of objects it is holding changes. If you need that do let me know, I have extended the Observable collection to have that feature also.

Share:
12,956
yoitsfrancis
Author by

yoitsfrancis

Updated on August 21, 2022

Comments

  • yoitsfrancis
    yoitsfrancis over 1 year

    I'm a newbie in events. This example shows that an event is invoked every time the ArrayList is changed. I would like to know how to do it using generics. To you implement IList or extend List? I tried to code it but I'm stuck.

    using System;
    using System.Collections.Generic;
    
    namespace Events
    {
        public delegate void ChangedEventHandler(object sender, EventArgs e);
    
        public class ListWithChangedEvent<T> : IList<T>
        {
            public event ChangedEventHandler Changed;
    
            protected virtual void OnChanged(EventArgs e)
            {
                if (Changed != null)
                {
                    Changed(this, e);
                }
            }
    
            public void Add(T value)
            {
                base.Add(value);
                OnChanged(EventArgs.Empty);
            }
    
            public void Clear()
            {
                base.Clear();
                OnChanged(EventArgs.Empty);
            }
    
            public T this[int index]
            {
                set
                {
                    base[index] = value;
                    OnChanged(EventArgs.Empty);
                }
            }
        }
    
        class EventListener
        {
            private ListWithChangedEvent<string> List;
    
            public EventListener(ListWithChangedEvent<string> list)
            {
                List = list;
                List.Changed += new ChangedEventHandler(ListChanged);
            }
    
            private void ListChanged(object sender, EventArgs e)
            {
                Console.WriteLine("This is called when the event fires.");
            }
    
            public void Detach()
            {
                List.Changed -= new ChangedEventHandler(ListChanged);
                List = null;
            }
        }
    
        class Program
        {
            public static void Main(string[] args)
            {
                ListWithChangedEvent<string> list = new ListWithChangedEvent<string>();
    
                EventListener listener = new EventListener(list);
    
                list.Add("item 1");
                list.Clear();
                listener.Detach();
            }
        }
    }