Search code examples
c#eventsinotifypropertychangedpropertychanged

Detect when register to the property change event


I have a Property Change event and I want to know when register to it.

Here my event in class1:

 public event PropertyChangedEventHandler PropertyChanged;

Here my register in class2 (MyObj is an instance of a Class1):

 MyObj.PropertyChanged += MyObj_PropertyChanged;

When the registration is happening, I want to run a specific function (from class1), how can I do it?

I could not find any way to do so...


Solution

  • Use this syntax to declare event:

    class MyClass
    {
        private EventHandler myEvent;
    
        private void OnEventHandlerRegistered()
        {
            Console.WriteLine("Event handler registered.");
        }
    
        public event EventHandler MyEvent
        {
            add 
            {
                myEvent += value;
                OnEventHandlerRegistered();
            }
            remove
            {
                myEvent -= value;
            }
        }
    }