简体   繁体   中英

How does an event handler of type PropertyChangedEventHandler get subscribed to PropertyChanged event?

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?

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.

eg

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);
    }

}

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