Search code examples
c#eventsobservablecollectioninotifycollectionchanged

Get the name of the object the event is registered on in C#


I have subscribed to the CollectionChanged event of an ObservableCollection<string> named m_myCollection like this:

  private ObservableCollection<string> m_myCollection;
  public ObservableCollection<string> MyCollection
  {
     get => m_myCollection;
     set
     {
        m_myCollection= value;
        OnPropertyChanged();
     }
  }

  public ViewModel()
  {
     MyCollection = new ObservableCollection<string>();

     MyCollection.CollectionChanged += OnCollectionChanged;

     MyCollection.Add("Item 1");
  }

  private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
  {
     // How to get the name of the collection here? That is: "MyCollection"
  }

How can I access the name of the collection within the method that is called when the CollectionChanged event is raised?


Solution

  • ObservableCollection instances don't have "names". And any number of variables might hold onto a reference to the collection. There could be none, there could be ten. There's no real "automatic" way of doing this. All you can really do is pass the information around yourself, for example by passing in what you consider the "name" of the collection to be to the handler:

     MyCollection = new ObservableCollection<string>();
     MyCollection.CollectionChanged += (s, e) => HandleCollectionChanged("MyCollection", e);
     MyCollection.Add("Item 1");
    

    Alternatively, you could make your own type of collection, possibly extending ObservableCollection, to give it a Name property that you set in the constructor, and can then read later.