0

I have subscribed to CollectionChanged event of ObservableCollection<string> 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 do I get the name of the collection in the method?

Vahid
  • 4,369
  • 10
  • 55
  • 116

1 Answers1

1

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.

Servy
  • 193,745
  • 23
  • 295
  • 406
  • Thank you. I think this way, I will be able to avoid hard-coding it: `MyCollection.CollectionChanged += (s, e) => HandleCollectionChanged(nameof(MyCollection), e);` – Vahid Oct 22 '18 at 14:48