Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How INotifyPropertyChanged's PropertyChanged event get assigned?

I have following code and it is working fine.

public partial class MainWindow : Window
{
    Person person;

    public MainWindow()
    {
        InitializeComponent();

        person = new Person { Name = "ABC" };

        this.DataContext = person;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        person.Name = "XYZ";
    }
}

class Person: INotifyPropertyChanged
{
    string name;

    public string Name
    { 
        get
        {
            return name;
        } 
        set
        {
            name = value;
            OnPropertyChanged("Name");
        } 
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string strPropertyName)
    {
        if(null != PropertyChanged)
        {
            PropertyChanged(this, 
                            new PropertyChangedEventArgs(strPropertyName));
        }           
    } 
}

When I create the "person" object in the constructor of MainWindow, it will assign the value for "Name" property of person, that time PropertyChanged event is NULL.

If the same "person" class property "Name" assigned in Button_Click event, "PropertyChanged" event is NOT NULL and it is pointing to OnPropertyChanged.

My question is how "PropertyChanged" event is assigned to OnPropertyChanged method?

Thanks in advance.

like image 620
Syed Avatar asked Sep 16 '11 02:09

Syed


People also ask

How PropertyChanged event works?

The PropertyChanged event can indicate all properties on the object have changed by using either null or String. Empty as the property name in the PropertyChangedEventArgs. Note that in a UWP application, String.

What is Notify property changed?

The INotifyPropertyChanged interface is used to notify clients, typically binding clients, that a property value has changed. For example, consider a Person object with a property called FirstName .


2 Answers

The WPF data-binding infrastructure will add a PropertyChanged handler when you set the object as a DataContext, in order to detect changes to your properties.
You can watch this happen by setting a breakpoint.

The OnPropertyChanged method that it points to is an internal WPF method, as you can see by inspecting the Target property of the delegate.

like image 90
SLaks Avatar answered Oct 04 '22 21:10

SLaks


The event will be null until something is subscribed to it. By the time the button click event has happened, it has a subscriber (via the databinding system).

like image 38
Phil Sandler Avatar answered Oct 04 '22 21:10

Phil Sandler