Skip to content
Tutorials Center
My learning

Topics

Lesson 167 of 182 ยท Advanced C#

INotifyPropertyChanged and MVVM

Learn how data binding works in C# - INotifyPropertyChanged, a reusable base class, ObservableCollection, commands and validation - with a tiny binding engine you can run and step through.

Desktop and mobile UI frameworks such as WPF, MAUI, Avalonia and Uno share one big idea: you describe what the screen shows ("this label shows the customer's name") and the framework keeps it up to date. You do not write label.Text = customer.Name after every change. That feature is called data binding, and it only works if the framework can find out when your data changes. In .NET that conversation happens through a few small interfaces in the base library: INotifyPropertyChanged, INotifyCollectionChanged, ICommand and INotifyDataErrorInfo.

This lesson builds the pattern from the bottom. You will write a reusable base class for view-models, see why computed properties need extra notifications, use ObservableCollection<T>, and then write a tiny binding engine yourself, about 40 lines, so that the framework stops being magic. Everything here is plain C#, so it runs in the browser editor. The earlier lesson on games and desktop apps introduced MVVM with a first counter example; this lesson goes deeper. It relies on events, properties and generics.

The problem binding solves

Imagine a form with a first name box, a last name box and a label showing the full name. Without binding you write event handlers that copy values around, and every new field means more copying and more bugs. With binding, the label and the text boxes are tied to properties of one object, the view-model. The view-model has no idea which controls exist; it only raises a signal when something changes.

sequenceDiagram
    participant V as View (controls)
    participant B as Binding engine
    participant VM as ViewModel
    V->>B: user types in the text box
    B->>VM: set FirstName = "Ada"
    VM-->>B: PropertyChanged("FirstName")
    VM-->>B: PropertyChanged("FullName")
    B->>V: update the label from FullName

The view never talks to the view-model directly: the binding engine listens to PropertyChanged and copies values in both directions.

The contract that makes this possible is one event:

C#
public interface INotifyPropertyChanged
{
    event PropertyChangedEventHandler? PropertyChanged;
}
// PropertyChangedEventArgs carries only the property NAME (a string).

When a property setter changes its value, it raises PropertyChanged with the property name. The binding engine subscribed to that event re-reads the property and updates the control. Passing "" or null as the name means "everything changed".

A base class so you write it once

Raising the event by hand in every property is repetitive and easy to get wrong. The standard solution is a small base class with a SetProperty helper. Two attributes make it pleasant: [CallerMemberName] fills in the property name for you, and an equality check avoids pointless notifications. The first example also shows the most common trap: a computed property such as FullName has no setter of its own, so nothing tells the UI to refresh it when FirstName changes unless you raise its notification as well.

C# An ObservableObject base class with a computed property

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The second assignment of "Ada" raised nothing, which matters for performance and for avoiding infinite loops (more on that shortly). Setting LastName raised two notifications because two bound values are now stale. Forgetting the nameof(FullName) line is the classic bug: the label keeps showing the old name until something else refreshes it.

Use nameof(...) instead of string literals. If you rename the property, the compiler updates or flags every notification. In real projects the CommunityToolkit.Mvvm package generates this boilerplate for you with attributes such as [ObservableProperty] and [NotifyPropertyChangedFor(nameof(FullName))], using source generators. Knowing the hand-written version tells you exactly what the generator produces.

Collections: INotifyCollectionChanged

A property change signal is not enough for lists. If a List<T> gains an item, nothing tells a ListView to add a row. The interface for that is INotifyCollectionChanged, and the ready-made implementation is ObservableCollection<T> (in System.Collections.ObjectModel). It raises CollectionChanged with an action (Add, Remove, Replace, Move, Reset) and details about which items were affected, so a list control can update just the affected rows instead of rebuilding everything.

Two rules to remember:

  1. ObservableCollection<T> notifies about adding and removing items. It does not notify when a property inside an item changes. For that, the item type must implement INotifyPropertyChanged itself, and the row template binds to it.
  2. Replace the whole collection property (Items = new(...)) only if the property itself raises PropertyChanged; otherwise bound controls keep listening to the old collection.
C# ObservableCollection and its change notifications

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Each operation raised a precise event, which is what lets a UI animate a single inserted row. Note that one AddRange-style bulk insert is not built in: adding 1,000 items one by one raises 1,000 events. UI code that loads big lists often builds a fresh collection and assigns it once.

Commands: ICommand

A button should not contain logic like "if the form is valid, save". The pattern is to put that in the view-model as an ICommand, an object with Execute, CanExecute and a CanExecuteChanged event. The framework disables the button while CanExecute returns false and re-asks whenever CanExecuteChanged fires. That last part is what beginners forget: if the answer to CanExecute depends on a property, you must raise CanExecuteChanged when that property changes, or the button stays greyed out.

The next example builds a RelayCommand that supports this, plus a form with validation through INotifyDataErrorInfo (the interface UI frameworks use to show red borders and messages next to fields). Together they show the whole loop: type, validate, enable the button.

C# Validation and a command that enables itself

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Every keystroke runs validation, which can add, change or clear the list of errors for that one property and raises ErrorsChanged only when it matters. After each validation the command re-announces itself, and in a real window the button would switch between enabled and disabled at exactly the lines printed here. The view-model contains no controls at all, so you can unit test the whole form by setting properties and checking SaveCommand.CanExecute.

Writing your own binding engine

Now the magic part. A binding is just: subscribe to PropertyChanged on the source, and when the property of interest changes, copy the value to the target. For two-way bindings you also subscribe to the target's change signal and copy back. Reflection finds the property by name, which is exactly what {Binding Name} in XAML does (the reflection cost is why compiled bindings exist in modern frameworks).

flowchart LR
    S["Source object<br/>(view-model)"] -- "PropertyChanged" --> E["Binding<br/>engine"]
    E -- "set value" --> T["Target object<br/>(control)"]
    T -. "PropertyChanged<br/>(two-way only)" .-> E
    E -. "set value" .-> S

One-way bindings follow the solid arrows; two-way bindings add the dotted return path, which is why equality checks are needed to stop an endless ping-pong.

C# A 40-line binding engine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Follow the output step by step. Setting the view-model updates both controls. Typing in the text box (two-way) pushes the text back into the view-model, which raises its own PropertyChanged, which updates the label, and the equality check in Copy stops the text box from being "updated" with the value it already holds. The label is one-way, so writing to it does not reach the source. Finally, Dispose unsubscribes; forgetting to unsubscribe is the standard memory leak in event-driven UIs, because a long-lived view-model holds a reference to every short-lived control that ever bound to it (see garbage collection).

Where MVVM goes wrong

  • Code in the view's code-behind. Logic placed there cannot be unit tested. Keep code-behind for pure view concerns (focus, animations).
  • Forgetting dependent notifications. Computed properties and commands need explicit notifications, as in the first and third examples.
  • Updating from background threads. Controls may only be touched on the UI thread. A PropertyChanged raised from a worker thread can crash the app; marshal back with the framework's dispatcher or SynchronizationContext (see async/await).
  • View-models that know about views. If a view-model opens dialogs or references Window, it is no longer testable. Use an interface (IDialogService) the view layer implements.
  • Huge ObservableCollection churn. Raising thousands of events individually is slow; swap in a new collection instead.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a property setter do to make a bound label refresh?

    The view-model never touches controls. It raises INotifyPropertyChanged.PropertyChanged, and the binding engine re-reads the property and updates the target.
  2. 2. FullName is a read-only property computed from FirstName and LastName. The UI shows a stale name after FirstName changes. What is missing?

    Nothing notifies the UI that FullName changed unless you raise it yourself. SetProperty only announces the property it wrote.
  3. 3. Which statement about ObservableCollection<T> is true?

    It reports structural changes only. Item property changes need INotifyPropertyChanged on the item type, and UI collections still have to be changed on the UI thread.
  4. 4. The Save button stays disabled even though the form is now valid. What is the most likely cause?

    The UI only re-evaluates CanExecute when CanExecuteChanged fires, so a view-model must raise it when the inputs of CanExecute change.
  5. 5. Why does SetProperty compare the old and new values before raising the event?

    With two-way bindings, a change in one side updates the other, which would notify back again. The equality check ends the loop and avoids redundant UI work.

Summary

  • Data binding keeps the UI in sync by listening to INotifyPropertyChanged.PropertyChanged; the view-model never references controls.
  • Put SetProperty in a base class, use [CallerMemberName] and nameof, and skip notifications when the value did not change.
  • Computed properties and commands need their own notifications (PropertyChanged for the property, CanExecuteChanged for the command).
  • ObservableCollection<T> reports adds, removes, replaces and moves; item property changes need INotifyPropertyChanged on the items.
  • INotifyDataErrorInfo lets a view-model publish validation errors per property, and everything stays unit-testable.
  • A binding is subscribe-and-copy; always unsubscribe, and keep UI-thread rules in mind.

Next: Desktop and Mobile UI: WPF, WinForms, MAUI