¿Generar evento cuando una lista tiene un nuevo elemento? [duplicar]

I write a control that displays a list of items (in this case just strings). I gave the developer a list of items where he can add and remove items (see code below). I wished there would be a way to be notified when a new item has been added and stuff. So as a reaction the control can update.

private List<string> items = new List<string>();

public List<string> Items
{ get { return items; } }

Cómo puedo hacer eso ? List<...> has no events. What can I do ?

preguntado el 05 de febrero de 14 a las 15:02

2 Respuestas

Echa un vistazo a BindingList<T> y ObservableCollection<T>. Esta respuesta explica la diferencia entre los dos.

Apart from binding, you can subscribe to the change events like so:

BindingList<T>.ListChanged:

items.ListChanged += (sender, e) => {
    // handle the change notification
};

ObservableCollection<T>.CollectionChanged:

items.CollectionChanged += (sender, e) => {
    // handle the change notification
};

contestado el 23 de mayo de 17 a las 13:05

Thx, for additional information and code. Good answer. - Azul amargo

Utilice la herramienta ObservableCollection<string> en lugar de un List. That class comes with built-in support for change notification events.

Respondido 05 Feb 14, 15:02

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.