← All lessons

Level 1 / XAML + MVVM / lesson 4 of 6

Commands instead of click handlers

Expose an ICommand on the view model and bind a button to it.

MVVM replaces click handlers with commands. The button does not know what happens when it is pressed; it only knows the name of a command on the view model. That is what keeps the view model testable without a UI.

Understand the idea

Commands separate intent from controls

A button binds to an ICommand. The view model decides what happens, which makes the behavior testable without clicking a UI.

The command needs an implementation

ICommand is an interface, not a ready-made RelayCommand class. A real app needs your own implementation or a library such as CommunityToolkit.Mvvm.

Changing data must notify the view

The command can change Count, but the display only follows if Count raises a change notification. Binding a button and refreshing a label are related but distinct tasks.

13 lines
5 lines

Preview - simulated. Not a .NET compiler.

0

Step 1 of 3

In progress

Expose a command

Add an ICommand property named IncrementCommand whose body runs Count++.

  • MainViewModel exposes a command named IncrementCommand - not done yet

Coach

The checklist above is what decides whether a step is done. The coach only explains; it never grades.

The preview is a simulated XAML surface, not WPF, WinUI, or .NET MAUI. It renders StackPanel, Grid, TextBlock, Label, TextBox, Entry, and Button, and simulates INotifyPropertyChanged and ICommand. Layout attributes such as Margin and Width are accepted but not laid out. Anything else is reported as outside the lesson.

Where the simulator stops

The exercise accepts a compact RelayCommand expression for simulation. A production command also needs appropriate lifetime, error handling, and often CanExecute/CanExecuteChanged behavior.

Try it in a real .NET project

In a WPF app, implement or install a relay command, bind an Add one button to IncrementCommand, and unit-test that executing the command increments Count. Bind a TextBlock to Count and verify notification updates the UI.

Check your understanding

Why bind a button to ICommand rather than write its business action only in a click handler?

Show the explanation

The view model owns the action, so you can test it without a window or button. The view declares the binding while the command supplies behavior and, when needed, CanExecute.

Goose School teaches Microsoft's stack. Goose Solutions is not affiliated with, endorsed by, or sponsored by Microsoft.