开发者

How to have Lists with events upon change in List

开发者 https://www.devze.com 2023-01-26 05:26 出处:网络
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 t

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.Cl开发者_开发知识库ear();
            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();
        }
    }
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消