Module 2 · Lesson 05 of 16
Commands, not click handlers
Properties for state, commands for intent, and a computed total that recalculates itself. No control is touched from code-behind.
MVVM is not a framework requirement. It is a rule about where state lives: in objects that can be constructed and exercised without a window.
using System.Collections.ObjectModel;
using System.ComponentModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
namespace CourseApp.Lessons.Mvvm;
public partial class CartItem(string name, decimal price) : ObservableObject
{
public string Name { get; } = name;
public decimal Price { get; } = price;
[ObservableProperty]
private int _quantity = 1;
}
public partial class CartViewModel : ObservableObject
{
public ObservableCollection<CartItem> Items { get; } =
[
new("Mechanical keyboard", 129.00m),
new("USB-C dock", 89.50m),
new("Desk mat", 24.00m),
];
[ObservableProperty]
private CartItem? _selected;
[ObservableProperty]
private string _status = "Nothing ordered yet.";
public decimal Total => Items.Sum(i => i.Price * i.Quantity);
public CartViewModel()
{
foreach (var item in Items)
item.PropertyChanged += OnItemChanged;
}
void OnItemChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(CartItem.Quantity))
OnPropertyChanged(nameof(Total));
}
[RelayCommand]
private void Increase() => ChangeQuantity(1);
[RelayCommand]
private void Decrease() => ChangeQuantity(-1);
void ChangeQuantity(int delta)
{
if (Selected is null)
return;
Selected.Quantity = Math.Max(1, Selected.Quantity + delta);
Status = $"{Selected.Name}: {Selected.Quantity} in the cart.";
}
[RelayCommand(CanExecute = nameof(CanCheckout))]
private void Checkout() => Status = $"Order placed for {Total:0.00}.";
bool CanCheckout() => Items.Count > 0 && Items.Sum(i => i.Quantity) > 0;
}
Commands are the verbs
[RelayCommand] generates an ICommand for each method. The view binds to it:
<Button Content="Checkout" Command="{Binding CheckoutCommand}" />
The button never calls Checkout(). It asks the command whether it can execute
and then executes it. That indirection buys two things you cannot get from a click
handler: the button disables itself, and the decision is testable.
[RelayCommand(CanExecute = nameof(CanCheckout))]
void Checkout() => Status = $"Order placed for {Total:0.00}.";
Computed state has to announce itself
Total is a plain expression over the collection:
public decimal Total => Items.Sum(i => i.Price * i.Quantity);
But a binding cannot observe an expression. When a quantity changes, the view
model raises PropertyChanged(nameof(Total)) explicitly. The sample subscribes to
each item's PropertyChanged in the constructor. That is the whole mechanism —
[ObservableProperty] on a field would not have helped here, because the change
happens on a child object.
The classic bug. Forgetting the notification. The value is correct in the debugger, the label on screen is stale, and you spend an hour looking at the binding instead of the view model.
Property or command?
- A value the user reads or edits → property, usually two-way.
- An action with a beginning and an end → command.
- A value derived from other values → computed property plus an explicit notification.
- Something that takes time → async command (next lesson).
Try it
- Add a
Clear cartcommand that removes every item and disables itself when the cart is empty. - Add a discount percentage property and apply it in
Total. Remember to notify. - Write the assertion for it in
LessonCatalog, run the verifier, and watch it fail before you fix the notification. That failure is the lesson.
Files this lesson draws from
src/CourseApp/Lessons/05_Mvvm/CartViewModel.cssrc/CourseApp/Lessons/05_Mvvm/CartView.axaml
VerifiedThe verifier checks that checkout is available, increases a quantity, asserts the total recomputes, and confirms the quantity never drops below one.