How to create events in C#?

Asked

Viewed 101 times

0

I have two classes one that has a list and I would like to have an event that every time that list was changed that 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");
    }
}

2 answers

5

Explanation

There is a type of Collection in C# that notifies changes made to the list through events, the Observablecollection.

With it, you can assign a method to the event CollectionChanged to receive change notifications in the list and also use the event PropertyChanged to receive notifications of changes to 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 on Dotnetfiddle

1


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

    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

  • But what if that list is not stated in the main ?

  • This was just an example. You can declare where you want, as long as the reference is valid.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.