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.
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.
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 .
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With