简体   繁体   English

ObservableCollection CollectionChanged事件似乎没有被解雇 - 为什么?

[英]ObservableCollection CollectionChanged event seems not to be firing – why?

What's wrong with this code? 这段代码出了什么问题? Clicking button1 doesn't cause the messageBox to appear. 单击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();
    }
}

With myClass defined: 使用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());
    }
}

EDIT: When I add a 3rd button with: 编辑:当我添加第3个按钮时:

private void button3_Click(object sender, EventArgs e)
{
    mc.myCollection.Add("a");
}

It does show the messageBox. 它确实显示了messageBox。 And so does button2. button2也是如此。 But after clicking button1 – none will fire anymore. 但点击button1后 - 没有人会再点火了。 How come? 怎么会?

You added an event handler to the original ObservableCollection instance from your field initializer. 您从字段初始值设定项向原始ObservableCollection实例添加了一个事件处理程序。
You never added an event handler to the new ObservableCollection instance from the form. 您从未向表单中的新ObservableCollection实例添加事件处理程序。
Since the original ObservableCollection never changes, your handler never runs. 由于原始的ObservableCollection永远不会更改,因此您的处理程序永远不会运行。

This is one of the many reasons why collection properties should be read only (and they should be properties, not fields ) 这是集合属性应该只读的众多原因之一( 它们应该是属性,而不是字段

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM