View models

A view model is the object a form binds to: it holds the values a screen shows, it raises PropertyChanged when one of them changes, and it has no controls in it. Where a presenter is told what the user did, a view model is observed by the controls. The two patterns meet in the same application; this lesson is the observed one.

A view model

One invoice line, with a quantity, a unit price and a total that is computed rather than stored:

internal sealed class LineViewModel : INotifyPropertyChanged { private decimal _quantity = 1; private decimal _unitPrice = 10m; public decimal Quantity { get => _quantity; set { if (_quantity == value) { return; } _quantity = value; OnPropertyChanged(); OnPropertyChanged(nameof(Total)); } } public decimal UnitPrice { get => _unitPrice; set { if (_unitPrice == value) { return; } _unitPrice = value; OnPropertyChanged(); OnPropertyChanged(nameof(Total)); } } public decimal Total => Math.Round(Quantity * UnitPrice, 2); public event PropertyChangedEventHandler? PropertyChanged; private void OnPropertyChanged([CallerMemberName] string? name = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); }

Four decisions are in that class, and each has a reason a form teaches:

Binding the form to it

The controls are bound once, in the constructor, and after that the form has no code that moves values. This is the whole program, built and not run:

using System; using System.ComponentModel; using System.Drawing; using System.Runtime.CompilerServices; using System.Windows.Forms; internal static class Program { [STAThread] private static void Main() { ApplicationConfiguration.Initialize(); Application.Run(new InvoiceForm()); } } internal sealed class LineViewModel : INotifyPropertyChanged { private decimal _quantity = 1; private decimal _unitPrice = 10m; public decimal Quantity { get => _quantity; set { if (_quantity == value) { return; } _quantity = value; OnPropertyChanged(); OnPropertyChanged(nameof(Total)); } } public decimal UnitPrice { get => _unitPrice; set { if (_unitPrice == value) { return; } _unitPrice = value; OnPropertyChanged(); OnPropertyChanged(nameof(Total)); } } public decimal Total => Math.Round(Quantity * UnitPrice, 2); public event PropertyChangedEventHandler? PropertyChanged; private void OnPropertyChanged([CallerMemberName] string? name = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); } internal sealed class InvoiceForm : Form { private readonly LineViewModel _line = new(); public InvoiceForm() { Text = "Invoice line"; ClientSize = new Size(360, 160); var quantity = new NumericUpDown { Location = new Point(120, 18), Maximum = 1000, DecimalPlaces = 0, }; var price = new NumericUpDown { Location = new Point(120, 50), Maximum = 10000, DecimalPlaces = 2, }; var total = new Label { Location = new Point(120, 90), AutoSize = true }; quantity.DataBindings.Add( nameof(NumericUpDown.Value), _line, nameof(LineViewModel.Quantity), false, DataSourceUpdateMode.OnPropertyChanged); price.DataBindings.Add( nameof(NumericUpDown.Value), _line, nameof(LineViewModel.UnitPrice), false, DataSourceUpdateMode.OnPropertyChanged); total.DataBindings.Add( nameof(Label.Text), _line, nameof(LineViewModel.Total), true, DataSourceUpdateMode.Never, string.Empty, "0.00"); Controls.Add(new Label { Text = "&Quantity:", AutoSize = true, Location = new Point(16, 22) }); Controls.Add(new Label { Text = "&Unit price:", AutoSize = true, Location = new Point(16, 54) }); Controls.Add(new Label { Text = "Total:", AutoSize = true, Location = new Point(16, 90) }); Controls.Add(quantity); Controls.Add(price); Controls.Add(total); } }

dotnet build app.csproj

Build succeeded.
    0 Warning(s)
    0 Error(s)

The listing is built and not run. The three Add calls are the whole connection: the first two are two-way, with OnPropertyChanged as the update mode, so a value typed into the box reaches the view model as it is typed. The third is one-way, DataSourceUpdateMode.Never, because a label cannot be edited, and its format string "0.00" is the one the binding uses to render the decimal.

formattingEnabled is the true argument of the label binding. Without it the format string is ignored. The empty string after Never is the null value: what the label shows when the binding has no data, which cannot happen here because the view model exists before the binding.

The events of one edit

The view model alone, with a handler that prints every property name. It was built and run here:

using System; using System.ComponentModel; using System.Runtime.CompilerServices; Console.WriteLine("one line, three edits"); var line = new LineViewModel(); line.PropertyChanged += (sender, e) => Console.WriteLine($"changed: {e.PropertyName}"); Console.WriteLine($"start: quantity {line.Quantity}, total {line.Total}"); line.Quantity = 3; Console.WriteLine($"after 3: total {line.Total}"); line.Quantity = 3; Console.WriteLine("set the same value again"); line.UnitPrice = 2.50m; Console.WriteLine($"after 2.50: total {line.Total}"); internal sealed class LineViewModel : INotifyPropertyChanged { private decimal _quantity = 1; private decimal _unitPrice = 10m; public decimal Quantity { get => _quantity; set { if (_quantity == value) { return; } _quantity = value; OnPropertyChanged(); OnPropertyChanged(nameof(Total)); } } public decimal UnitPrice { get => _unitPrice; set { if (_unitPrice == value) { return; } _unitPrice = value; OnPropertyChanged(); OnPropertyChanged(nameof(Total)); } } public decimal Total => Math.Round(Quantity * UnitPrice, 2); public event PropertyChangedEventHandler? PropertyChanged; private void OnPropertyChanged([CallerMemberName] string? name = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); }

dotnet run

one line, three edits
start: quantity 1, total 10
changed: Quantity
changed: Total
after 3: total 30
set the same value again
changed: UnitPrice
changed: Total
after 2.50: total 7.50

The output is the real run. One assignment to Quantity raised two events, Quantity and Total, because two bindings depend on it. Assigning the same value again raised nothing, which is the early return doing its work. The two events refreshed the two bindings that depend on them: the box bound to Quantity and the label bound to Total. One edit, two refreshes, and each is the refresh its binding needs; the alternative is a computed property that nothing tells the label to re-read.

A list of view models

A grid binds to a collection, and BindingList<T> is the collection that tells it about every change. The invoice below owns a list of lines and a total over them. It was built and run here:

using System; using System.ComponentModel; using System.Runtime.CompilerServices; Console.WriteLine("an invoice of two lines"); var invoice = new InvoiceViewModel(); invoice.PropertyChanged += (sender, e) => Console.WriteLine($"invoice changed: {e.PropertyName}"); invoice.Lines.ListChanged += (sender, e) => Console.WriteLine($"list {e.ListChangedType}, lines {invoice.Lines.Count}, total {invoice.Total}"); invoice.Lines.Add(new LineViewModel { Quantity = 2, UnitPrice = 3.50m }); invoice.Lines.Add(new LineViewModel { Quantity = 4, UnitPrice = 1.25m }); invoice.Lines.RemoveAt(0); invoice.Lines[0].Quantity = 10; Console.WriteLine($"after editing the first line: total {invoice.Total}"); internal sealed class InvoiceViewModel : INotifyPropertyChanged { public InvoiceViewModel() { Lines.ListChanged += (sender, e) => OnPropertyChanged(nameof(Total)); } public BindingList<LineViewModel> Lines { get; } = new(); public decimal Total { get { var sum = 0m; foreach (var line in Lines) { sum += line.Total; } return Math.Round(sum, 2); } } public event PropertyChangedEventHandler? PropertyChanged; private void OnPropertyChanged([CallerMemberName] string? name = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); } internal sealed class LineViewModel : INotifyPropertyChanged { private decimal _quantity = 1; private decimal _unitPrice; public decimal Quantity { get => _quantity; set { if (_quantity == value) { return; } _quantity = value; OnPropertyChanged(); OnPropertyChanged(nameof(Total)); } } public decimal UnitPrice { get => _unitPrice; set { if (_unitPrice == value) { return; } _unitPrice = value; OnPropertyChanged(); OnPropertyChanged(nameof(Total)); } } public decimal Total => Math.Round(Quantity * UnitPrice, 2); public event PropertyChangedEventHandler? PropertyChanged; private void OnPropertyChanged([CallerMemberName] string? name = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); }

dotnet run

an invoice of two lines
invoice changed: Total
list ItemAdded, lines 1, total 7.00
invoice changed: Total
list ItemAdded, lines 2, total 12.00
invoice changed: Total
list ItemDeleted, lines 1, total 5.00
invoice changed: Total
list ItemChanged, lines 1, total 12.50
invoice changed: Total
list ItemChanged, lines 1, total 12.50
after editing the first line: total 12.50

The output is the real run, and it holds a fact that surprises most readers. A BindingList<T> subscribes to PropertyChanged of its items, so an edit to a line arrives as ItemChanged even though the line was not added or removed. The lesson 048 test with a plain class saw nothing, because a plain class raises nothing; a view model is what makes the list able to tell.

The edit raised ItemChanged twice, once for Quantity and once for Total, and the invoice total was recomputed twice. That is correct and slightly wasteful; a view model with many computed properties can coalesce its notifications, and a screen with a thousand rows should. The invoice raises one PropertyChanged per list event, which also means the handler order matters: the invoice subscribed in its constructor, before the program subscribed, so its line comes first.

Exercises

  1. Add a Discount property to the line and the third OnPropertyChanged call, then count the events for one edit.
  2. Add a LineRemoved event to the invoice, raise it from the list handler and print the removed line from the program.
  3. Bind the invoice total of the last program to a label in the form of the second section and explain which handler refreshes it.

Questions

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

  1. What is a view model?

    Answer

    The object a form binds to, with the values and PropertyChanged and no controls

    It is observed by the controls instead of driving them.

  2. Why does Total raise its own PropertyChanged?

    Answer

    A binding to Total listens for the name Total, not Quantity

    Each bound property is refreshed by the event that names it.

  3. What does [CallerMemberName] do here?

    Answer

    Fills the parameter with the name of the calling property

    No property name is written twice, so a rename cannot break it.

  4. What did the run print when Quantity was set to 3?

    Answer

    changed: Quantity and changed: Total

    Two properties depend on the edit and two events were raised.

  5. What happened when the same value was assigned again?

    Answer

    Nothing was raised, because the setter returned early

    The early return is what the output shows.

  6. Which update mode lets a text box write to the view model as the user types?

    Answer

    DataSourceUpdateMode.OnPropertyChanged

    The invoice form uses it for both numeric boxes.

  7. Why is the label bound with DataSourceUpdateMode.Never?

    Answer

    A label cannot be edited, so data never flows back

    The mode describes the direction the control needs.

  8. What did the BindingList raise when a line property changed?

    Answer

    ItemChanged, because the list listens to the item

    A view model raises, so the list can pass the change on.

  9. Why did ItemChanged appear twice for one edit?

    Answer

    The line raised Quantity and Total

    One list event per property event of the item.

  10. What does the invoice view model subscribe to in its constructor?

    Answer

    Lines.ListChanged, to raise PropertyChanged for Total

    The list event is enough for the total, since the list passes item changes on.

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