0

)

Please have a look at the code below:

public class MyClass : INotifyPropertyChanged
{
    private string _myName;

    public string MyName
    {
        get { return _myName; }
        set
        {
            if (_myName != value)
            {
                _myName = value;
                OnPropertyChanged("MyName");
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;


    private void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

Object of this class is used as a DataContext for textBox control on WPF form.

Idea is simple: changes done to MyName property of this object should be automatically displayed in textBox. It works but I do not understand why.

Please follow my way of thinking and point out where I get it wrong...

We set a new value for MyName. Program goes to 'setter' and it calls 'OnPropertyChanged'. It goes to 'OnPropertyChanged' and checks if 'PropertyChanged' is null.

And it is not. And I do not know why since I do not add any event handlers to this event.

So... how does it work?

Thank you!

1
  • you should ideally change if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); to var handler =PropertyChanged; if (handler != null) handler (this, new PropertyChangedEventArgs(propertyName)); as if the propertychanged handler is changed between the if check and the call then you get a null ref exception
    – MikeT
    Feb 18, 2014 at 15:41

1 Answer 1

1

The Event Handler is added automatically when you bind the object to the DataContext.

2
  • I noticed that if MyClass does not implement INotifyPropertyChanged then it does not work as wanted. What is the deeper meaning of implementing this interface here? Nov 1, 2013 at 22:21
  • 1
    @JacekWojcik - By implementing the interface, you indicate to WPF that you are responsible for notifying the framework when something changes and a field on your object needs to be re-rendered. If you don't implement the interface, you make no such promise to WPF and it tries to do something itself. Nov 1, 2013 at 23:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.