ObservableCollection CollectionChanged 事件似乎没有触发 –为什么?
这段代码有什么问题?单击button1 不会导致出现messageBox。
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();
}
}
定义 myClass 后:
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());
}
}
编辑: 当我添加第三个按钮时:
private void button3_Click(object sender, EventArgs e)
{
mc.myCollection.Add("a");
}
它确实显示消息框。 Button2 也是如此。但点击按钮1后——没有一个会再触发。怎么会?
What’s wrong with this code? Clicking button1 doesn’t cause the messageBox to appear.
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();
}
}
With myClass defined:
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:
When I add a 3rd button with:
private void button3_Click(object sender, EventArgs e)
{
mc.myCollection.Add("a");
}
It does show the messageBox. And so does button2. But after clicking button1 – none will fire anymore. How come?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您通过字段初始值设定项将事件处理程序添加到原始
ObservableCollection
实例。您从未将事件处理程序添加到表单中的新
ObservableCollection
实例。由于原始的 ObservableCollection 永远不会改变,因此您的处理程序永远不会运行。
这是集合属性应为只读(并且它们应该是属性,而不是字段)
You added an event handler to the original
ObservableCollection
instance from your field initializer.You never added an event handler to the new
ObservableCollection
instance from the form.Since the original
ObservableCollection
never changes, your handler never runs.This is one of the many reasons why collection properties should be read only (and they should be properties, not fields)