简体   繁体   中英

CollectionChanged Event is not firing on a static ObservableCollection

In one class I'm adding objects to my ObservableCollection. And in another class, I'm doing stuff with my added object and then delete it from the collection.

Those two classes cannot communicate with each other, so I decided to go for static collection (I only have access to the class definition for some reason)

In my first class, all elements are added properly (I checked the Count property), in the second class I subscribe to the CollectionChanged event. However, the event is not raising. I think it's because of the static keyword, but I'm not sure.

Here is a code sample:

static public class A
{
public static ObservableCollection<object> MyCollection = new ObservableCollection<object>();
}

public class B
{
public B()
{
A.MyCollection.CollectionChanged += Func_CollectionChanged;
}
 void Func_CollectionChanged(...)
{
  //Stuff
}
}
public class C
{
   public void func()
    {
    A.MyCollection.Add(object);
    }
}

Here it works fine for me:

 class Program
    {
        static void Main(string[] args)
        {
            B obj = new B();  
        }
    }
    public class A
    {
        public static ObservableCollection<object> MyCollection = new ObservableCollection<object>();
    }
    public class B
    {
        public B()
        {
            A.MyCollection.CollectionChanged += Func_CollectionChanged;
            A.MyCollection.Add(1);
        }

        private void Func_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            // do some stuff here
        }
    }

by using A.MyCollection.CollectionChanged line you are creating an EventHandler to handle the the collection change event. it fires when ever any changes(add/update/delete) made in the collection. since it is a delegate you are creating you have to specify the sender who own the event and the type of arguments(What it going to handle), in-order to get proper reporting of published event

Updates

You just look into your code. the instance of class b is not yet created, the constructor of this class will automatically invoked only when the new instance of the class is created. You are creating the Event handler inside the constructor of class b. So it is not yet published any event. that is the reason for the collection_Change event is not triggering in your code snippet.

Hence your Definition for class C will be like the following to register the event :

  public class C
    {
        B obj = new B();
        public void func()
    {          
    A.MyCollection.Add(1);
    }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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