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 "P开发者_运维技巧ropertyChanged" event is assigned to OnPropertyChanged method?
Thanks in advance.
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.
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).
精彩评论