¿Qué pasa con este código? Al hacer clic en el botón 1, no aparece el mensajeBox.ObservableCollection CollectionChanged evento parece no estar disparando, ¿por qué?
public partial class Form1 : Form
{
public ObservableCollection<string> aCollection2 = new ObservableCollection<string>();
myClass mc = new myClass();
public Form1()
{
InitializeComponent();
aCollection2.Add("a");
aCollection2.Add("b");
}
private void button1_Click(object sender, EventArgs e)
{
mc.myCollection = aCollection2;
}
private void button2_Click(object sender, EventArgs e)
{
mc.myCollection.Clear();
}
}
Con myClass definido:
class myClass
{
public ObservableCollection<string> myCollection = new ObservableCollection<string>();
public myClass()
{
myCollection.CollectionChanged += Changed;
}
void Changed(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
MessageBox.Show(myCollection.Count.ToString());
}
}
EDIT: Cuando agrego un botón tercero con:
private void button3_Click(object sender, EventArgs e)
{
mc.myCollection.Add("a");
}
sí muestra la messageBox. Y también lo hace button2. Pero después de hacer clic en el botón 1 - ninguno disparará más. ¿Cómo?
Ver edición. Dispara en ciertos casos. – ispiro
@ispiro: Exactamente. Solo se activa cuando modifica el ** original ** 'ObservableCollection', no después de reemplazarlo. – SLaks
Hacer que la colección sea de solo lectura reveló reasignaciones y me salvó de muchos dolores de cabeza. –