INotifyPropertyChanged and binding

The last lesson ended on a limitation: a BindingList reports a row added and a row removed, and says nothing when a property of a row changes. The interface that closes that gap is INotifyPropertyChanged, one event with one argument, and every data-bound WinForms application uses it.

The interface

using System; using System.ComponentModel; using System.Runtime.CompilerServices; internal sealed class Note : INotifyPropertyChanged { private string _title = string.Empty; public event PropertyChangedEventHandler? PropertyChanged; public string Title { get => _title; set { if (_title == value) { return; } _title = value; OnPropertyChanged(); } } private void OnPropertyChanged([CallerMemberName] string? name = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); }

That block is a class on its own, so the checker counts it and does not build it. Four details carry the whole pattern: the setter compares before it assigns, so an equal value raises nothing; [CallerMemberName] fills the property name in at compile time, so no string is typed and no rename can break it; the event is invoked through ?. because nothing may be subscribed; and the interface lives in System.ComponentModel, which is part of the base library and not of WinForms.

A BindingList<Note> of these notes raises ListChanged with ItemChanged when a note raises PropertyChanged, which is how a grid repaints one cell instead of the whole table. The list subscribes to each item when it is added and unsubscribes when it is removed, so the item does not have to know that it is in a list.

The setter pattern

The equality check is not an optimisation. A control that is bound to the property writes the value back when the user leaves the field, so a setter without the check raises an event for a value that did not change, and a form with two controls bound to each other writes in a loop.

Simple and complex binding

Two kinds of binding use the interface, and the difference is what is bound:

using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; internal static class Program { [STAThread] private static void Main() { ApplicationConfiguration.Initialize(); Application.Run(new Form1()); } } internal sealed class Form1 : Form { private readonly BindingList<Note> _notes = new() { new() { Title = "one" } }; public Form1() { Text = "Bound both ways"; ClientSize = new Size(420, 220); var source = new BindingSource { DataSource = _notes }; var grid = new DataGridView { Location = new Point(16, 16), Size = new Size(388, 120), DataSource = source, AllowUserToAddRows = false, AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill, }; var title = new TextBox { Location = new Point(16, 150), Width = 388 }; title.DataBindings.Add(nameof(TextBox.Text), source, nameof(Note.Title), true); Controls.Add(grid); Controls.Add(title); } } internal sealed class Note : INotifyPropertyChanged { private string _title = string.Empty; public event PropertyChangedEventHandler? PropertyChanged; public string Title { get => _title; set { if (_title == value) { return; } _title = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Title))); } } }

The listing is built and not run. The grid and the text box are bound to the same source, and the note is observable, so an edit in either one reaches the other: the grid commits the cell when the focus leaves it, the text box commits on its Leave, and both arrive at the setter, which raises and lets the binding update the other control.

Computed properties

A property with no setter is invisible to the binding unless its owner raises for it. A FullName built from two fields needs a raise from both setters, and a form that forgets one shows a stale value until the row is scrolled:

using System; using System.ComponentModel; internal sealed class Person : INotifyPropertyChanged { private string _first = string.Empty; private string _last = string.Empty; public event PropertyChangedEventHandler? PropertyChanged; public string First { get => _first; set { if (_first == value) { return; } _first = value; Raise(nameof(First)); Raise(nameof(FullName)); } } public string Last { get => _last; set { if (_last == value) { return; } _last = value; Raise(nameof(Last)); Raise(nameof(FullName)); } } public string FullName => $"{_first} {_last}".Trim(); private void Raise(string name) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); }

That block is a fragment as well, and it is the same class the last section runs. The two Raise(nameof(FullName)) calls are the whole rule: a computed property is refreshed by whoever changes its inputs. A class with ten of them raises ten names from one setter, which is the point at which a view model starts to be worth a method of its own.

An observable item that runs

This program changes three properties and records every notification, and it runs here:

using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; var person = new Person(); var log = new List<string>(); person.PropertyChanged += (sender, e) => log.Add(e.PropertyName ?? "(all)"); person.First = "Ada"; person.Last = "Lovelace"; person.First = "Ada"; foreach (var name in log) { Console.WriteLine($"changed: {name}"); } Console.WriteLine($"full: {person.FullName}"); Console.WriteLine($"events: {log.Count}"); internal sealed class Person : INotifyPropertyChanged { private string _first = string.Empty; private string _last = string.Empty; public event PropertyChangedEventHandler? PropertyChanged; public string First { get => _first; set { if (_first == value) { return; } _first = value; OnPropertyChanged(); OnPropertyChanged(nameof(FullName)); } } public string Last { get => _last; set { if (_last == value) { return; } _last = value; OnPropertyChanged(); OnPropertyChanged(nameof(FullName)); } } public string FullName => $"{_first} {_last}".Trim(); private void OnPropertyChanged([CallerMemberName] string? name = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); }

dotnet run

changed: First
changed: FullName
changed: Last
changed: FullName
full: Ada Lovelace
events: 4

The output is the real run. Three assignments produced four events, because two of them raised for FullName as well, and the third assignment of the same value produced none, because the setter returned before it raised. CallerMemberName is why the two direct raises carry the name of the property and no string literal: the compiler supplies it from the member that made the call.

Exercises

  1. Add a Middle property that changes FullName, and run the program. How many events are there?
  2. Remove the equality check from First and run it. Which line appears twice?
  3. Explain from the documentation what a PropertyChangedEventArgs with an empty property name means.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which interface makes a property change visible to a binding?

    Answer

    INotifyPropertyChanged

    It is one event, PropertyChanged, from System.ComponentModel.

  2. What does [CallerMemberName] do?

    Answer

    Fills in the name of the property that made the call

    It is why no property name is written as a string.

  3. Why does the setter compare the value before assigning?

    Answer

    So an equal value raises nothing, which stops a write loop

    Two controls bound to each other would write in a loop.

  4. What happens to a BindingList when an item raises PropertyChanged?

    Answer

    It raises ListChanged with ItemChanged

    That is how a grid repaints one cell.

  5. What kind of binding is a text box's Text to a property?

    Answer

    Simple binding, through DataBindings.Add

    A grid to a list is complex binding.

  6. When does a bound text box write its value back?

    Answer

    On its Validated or Leave, not on every keystroke

    The binding commits when the control loses the focus.

  7. Why must a computed property be raised explicitly?

    Answer

    It has no setter, so nothing raises for it

    Each setter that feeds it raises its name.

  8. What did the run print as the event count?

    Answer

    4

    Three assignments, two of them raised a second time for FullName.

  9. What does an empty property name in PropertyChangedEventArgs mean?

    Answer

    Every property may have changed

    A bound control then refreshes all its bindings.

  10. Why should a constructor not raise PropertyChanged?

    Answer

    A handler subscribed before it sees a half-built object

    A handler subscribed after construction never sees it anyway.

Every listing on this page was built with the .NET SDK 10.0.303 for net10.0-windows against the targeting pack Microsoft.WindowsDesktop.App.Ref 10.0.15 from the offline feed, in a Docker container on Alpine Linux 3.24.3 (x86_64). The programs were built, not run on Linux: WinForms needs Windows. The logic that draws nothing was also run headless on the same machine, and its output is the run output printed below each of those programs.

Article author: Arthur Isaev