How to create events in C #?

0

I have two classes one that has a list and I would like to have an event that every time this list was changed this event was called.

public class Exemplo
{
    List<string> lista = new List<string>();
    //Quando esta lista foi alterada
}

public class Exemplo1
{
    protected virtual void QuandoListaAlterada(EventArgs e)
    {
        MessageBox.Show("Lista Foi Alterada");
    }
}
    
asked by anonymous 09.07.2018 / 19:28

2 answers

1

One way is to extend the List class by adding an event, like this:

    using System;
    using System.Collections.Generic;

    namespace teste
    {
        class Program
        {

            class ListaComEventos<T> : List<T>
            {

                public event EventHandler OnAdicionar;

                public void Adicionar(T item)
                {
                    if (OnAdicionar != null)//verifica se evento foi especificado
                    {
                        OnAdicionar(this, null);
                    }
                    base.Add(item);
                }

            }

            static void Main(string[] args)
            {
                ListaComEventos<int> minhaLista = new ListaComEventos<int>();
                minhaLista.OnAdicionar += new EventHandler(EventoAdicionar);
                minhaLista.Adicionar(1);
                minhaLista.Adicionar(1);
                minhaLista.Adicionar(1);
                Console.ReadKey();
            }

            static void EventoAdicionar(object sender, EventArgs e)
            {
                Console.WriteLine("Um elemento foi adicionado");
            }
        }
    }

Here is the code running on .netFiddle

    
09.07.2018 / 19:51
5

Explanation

There is a collection type in C # that notifies changes made to the list through events, at ObservableCollection .

With it, you can assign a method in the CollectionChanged event to receive change notifications in the list and also use the PropertyChanged event to receive notification of changes in the properties.

Example

using System;
using System.Collections.ObjectModel;

namespace ObservableCollectionExample
{
    class Program
    {
        static void Main(string[] args)
        {
            ObservableCollection<string> list = new ObservableCollection<string>();
            list.CollectionChanged += List_CollectionChanged;

            list.Add("Teste 1");
            list.Add("Teste 2");
        }

        private static void List_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            Console.WriteLine("A lista foi alterada.");
        }
    }
}

See working at DotNetFiddle

    
09.07.2018 / 20:03