How is the INotifyPropertyChanged PropertyChanged event assigned?

I have the following code and it works 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 a person object in the MainWindow constructor, it will assign a value for the Name property to the person, then the PropertyChanged event is NULL .

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

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

Thanks in advance.

+6
source share
2 answers

The WPF data binding framework will add a PropertyChanged handler when you set the object as a DataContext to detect changes in your properties.
You can observe how this happens by setting a breakpoint .

Method OnPropertyChanged , it points to is an internal method of a WPF, as you can see by checking the property Target delegate.

+5
source

The event will be null until something subscribes to it. By the time the button click event has occurred, he has a subscriber (via the data binding system).

+2
source

Source: https://habr.com/ru/post/897436/


All Articles