1

I have a class of type TEntity which is bound to a View:

 public class TEntity
    {
     private string _name;
     public string Name 
     { 
        get {return _name;} 
        set {_name = value; NotifyPropertyChanged("Name");}  
     }
     public event PropertyChangedEventHandler PropertyChanged;
     private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
     {
       if(PropertyChanged != null)
       {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
       }
     }

I have not subscribed to PropertyChanged event anywhere in my code, but whenever I change the value of Name property an event handler gets subscribed to PropertyChanged event. I have not created any handler in my code. How is that handler created and subscribed appropriately?

leppie
  • 115,091
  • 17
  • 196
  • 297
Suraj
  • 609
  • 6
  • 13

1 Answers1

0

Your code implements the raising of the event 'PropertyChanged', not the subscription.

It is up to the consumer of your code to subscribe to that event, and provide a handler.

e.g.

public class DisplayEntiry
{
    public void Initialize()
    {
        var entity = new Entity();
        entity.PropertyChanged += DisplayName;

        entity.Name = "Alan Bennett";  
        // This will cause DisplayName to write "Alan Bennett" to the console
    }

    private void DisplayName(object sender, PropertyChangedEventArgs e)
    {
        Console.Writeline(e.Name);
    }

}
Phillip Ngan
  • 15,482
  • 8
  • 63
  • 79
  • I got your point. My question here is as soon as I assign a value to the property which is bound to UI an event handler gets created automatically, i.e PropertyChanged != null. Nowhere in my code I have written a handler.So I was curious as to how the handler gets created. – Suraj Feb 12 '15 at 10:59