7

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.

Syed
  • 931
  • 13
  • 28
  • You should really do your onpropertychanged as `var handler=PropertyChanged; if (null!=handler) handler(this,new PropertyChangedEventArgs(strPropertyName)` this will help you avoid a race condition – Bob Vale Sep 16 '11 at 02:15

2 Answers2

6

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.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
2

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

Phil Sandler
  • 27,544
  • 21
  • 86
  • 147
  • Thanks for your answer, but it is contracting with SLaks answer. I'm confused which is correct? – Syed Sep 16 '11 at 02:23
  • 1
    @Syed: He isn't contradicting me; he's just providing less detail. Until WPF subscribes to the event (when you bind to the model), it's `null`. – SLaks Sep 16 '11 at 14:20
  • 1
    Another way to say it is my answer is more concise. :) Just kidding, SLaks answer explains it much better. – Phil Sandler Sep 16 '11 at 14:43