开发者

How INotifyPropertyChanged's PropertyChanged event get assigned?

开发者 https://www.devze.com 2023-04-05 11:09 出处:网络
I have following code and it is working fine. public partial class MainWindow : Window { Person person; public MainWindow()

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).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号