using of INotifyPropertyChanged

Can someone explain me why need to use implementation of INotifyPropertyChanged when using binding in wpf? I can bind properties without implementation of this interface? For example i have code

public class StudentData : INotifyPropertyChanged
{
    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;
    #endregion

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

    string _firstName = null;
    public string StudentFirstName
    {
        get
        {
            return _firstName;
        }
        set
        {
            _firstName = value;

            OnPropertyChanged("StudentFirstName");
        }
    }
}

And binding in .xaml

<TextBox Text="{Binding Path=StudentFirstName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
   Grid.Row="1"
   Grid.Column="2"
   VerticalAlignment="Center" />

this code from .xaml.cs

StudentData _studentData = new StudentData { StudentFirstName = "John", StudentGradePointAverage = 3.5};

public MainWindow()
{
    InitializeComponent();

    this.DataContext = _studentData;
}

why we need to use INotifyPropertyChanged in this case? It is not my code.


You need INotifyPropertyChanged if you want a wpf form to be automatically updated when a property changes through code. Also some controllers might want to know if edits have been made in order to enable/disable a save-button, for instance. You also might be displaying the same property on different views; in this case INotifyPropertyChanged helps to immediately update the other view when you edit a property.

If you think that your form behaves well without INotifyPropertyChanged, then you can drop it.

Note that binding works even without INotifyPropertyChanged. See: Why does the binding update without implementing INotifyPropertyChanged?


I would implement the properties like this. In some rare cases it can help to avoid endless circular updates. And it is more efficient by the way.

 private string _firstName;
 public string StudentFirstName
 {
     get { return _firstName; }
     set
     {
         if (value != _firstName) {
             _firstName = value;
             OnPropertyChanged("StudentFirstName");
         }
     }
 }

Starting with C#6.0 (VS 2015), you can implement OnPropertyChanged like this:

private void OnPropertyChanged(string propertyName)
{
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}