wpf Introduction to WPF Data Binding Implementing INotifyPropertyChanged

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

INotifyPropertyChanged is an interface used by binding sources (i.e. the DataContext) to let the user interface or other components know that a property has been changed. WPF automatically updates the UI for you when it sees the PropertyChanged event raised. It is desirable to have this interface implemented on a base class that all of your viewmodels can inherit from.

In C# 6, this is all you need:

public abstract class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void NotifyPropertyChanged([CallerMemberName] string name = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }
}

This allows you to invoke NotifyPropertyChanged in two different ways:

  1. NotifyPropertyChanged(), which will raise the event for the setter that invokes it, thanks to the attribute CallerMemberName.
  2. NotifyPropertyChanged(nameof(SomeOtherProperty)), which will raise the event for SomeOtherProperty.

For .NET 4.5 and above using C# 5.0, this can be used instead:

public abstract class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void NotifyPropertyChanged([CallerMemberName] string name = null)
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }
}

In versions of .NET prior to 4.5, you have to settle for property names as string constants or a solution using expressions.


Note: It is possible to bind to a property of a "plain old C# object" (POCO) that does not implement INotifyPropertyChanged and observe that the bindings work better than expected. This is a hidden feature in .NET and should probably be avoided. Especially as it will cause memory leaks when the binding's Mode is not OneTime (see here).

Why does the binding update without implementing INotifyPropertyChanged?



Got any wpf Question?