Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 42 ยท MVVM and Navigation

The MVVM Pattern in .NET MAUI

Learn MVVM for .NET MAUI: the roles of Model, View and ViewModel, why it beats code-behind, a hand-written ObservableObject and a runnable ViewModel with change notifications, with no UI needed.

Model-View-ViewModel (MVVM) is the architecture .NET MAUI was designed for. It splits an app into three roles so that the screen can change without touching the logic, and the logic can be tested without a screen. If your pages have grown into hundreds of lines of code-behind full of entry.Text and label.Text = ..., MVVM is the cure.

MAUI itself cannot run on this site, so the XAML is read-only. A view model, however, is plain C#, and that is the whole point of MVVM: the runnable blocks here are real view-model code, and the only stand-in is a tiny console "view" that plays the part of the page.

The three roles

Role What it is Knows about
Model Data and business rules: Product, Order, services, repositories nothing about the UI
View XAML page plus a thin code-behind the view model (through binding)
ViewModel State and commands for one screen, exposed as properties the model, never the view

The arrows are one-directional: the view binds to the view model; the view model uses the model. A view model never holds a reference to a Label or a Page, so it never has to know what kind of screen shows it.

flowchart LR
    V["View<br/>(XAML page)"] -- "data binding<br/>commands" --> VM["ViewModel<br/>(state + commands)"]
    VM -- "notifies<br/>PropertyChanged" --> V
    VM --> M["Model<br/>(data, services)"]
    M --> VM

The view and the view model talk only through bindings and change notifications.

Why bother?

  • Testable: you can create a view model in a unit test and call its commands, no emulator needed.
  • Replaceable UI: the same view model can drive a phone page and a tablet page, or be reused when you redesign.
  • Smaller pages: code-behind shrinks to InitializeComponent() and a few UI-only handlers such as animation.
  • Teamwork: a designer edits XAML while a developer works on the view model.

For a tiny one-page app, code-behind is perfectly fine. MVVM pays off as soon as a screen has state that more than one control shows, validation or asynchronous work.

The view model

A view model exposes properties (state) and commands (actions), and raises PropertyChanged when state changes. The reusable part is a base class that implements INotifyPropertyChanged:

C#
using System.ComponentModel;
using System.Runtime.CompilerServices;

public abstract class ObservableObject : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler? PropertyChanged;

    protected bool SetProperty<T>(ref T field, T value, [CallerMemberName] string? name = null)
    {
        if (EqualityComparer<T>.Default.Equals(field, value)) return false;
        field = value;
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        return true;
    }

    protected void OnPropertyChanged([CallerMemberName] string? name = null) =>
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}

SetProperty removes the boilerplate: it assigns only if the value changed and raises the event. In the next lesson you will let the Community Toolkit generate this code; first it helps to see how it works by hand.

A complete view model

This counter-and-greeting view model follows every MVVM rule. Notice dependent properties: when Name changes, Greeting must be announced too.

C#
public class GreetingViewModel : ObservableObject
{
    private string name = "";
    private int clicks;

    public string Name
    {
        get => name;
        set
        {
            if (SetProperty(ref name, value))
            {
                OnPropertyChanged(nameof(Greeting));   // computed from Name
            }
        }
    }

    public string Greeting => string.IsNullOrWhiteSpace(Name) ? "Hello, stranger!" : $"Hello, {Name}!";

    public int Clicks { get => clicks; private set => SetProperty(ref clicks, value); }

    public void Click() => Clicks++;
}

And the matching view, read-only:

XML
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:vm="clr-namespace:HelloApp.ViewModels"
             x:Class="HelloApp.GreetingPage"
             x:DataType="vm:GreetingViewModel">

    <VerticalStackLayout Padding="24" Spacing="12">
        <Entry Placeholder="Your name" Text="{Binding Name}" />
        <Label Text="{Binding Greeting}" FontSize="24" />
        <Label Text="{Binding Clicks, StringFormat='Clicked {0} times'}" />
    </VerticalStackLayout>
</ContentPage>
C#
public partial class GreetingPage : ContentPage
{
    public GreetingPage(GreetingViewModel viewModel)
    {
        InitializeComponent();
        BindingContext = viewModel;
    }
}

The next block runs the same view model on Piston. A small FakeView plays the role of the page: it subscribes to PropertyChanged and prints what a real label would show. The view model and its base class are real, unchanged C#.

C# Run a real view model without a UI

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.

What belongs where

A useful rule of thumb:

  • View: layout, visual states, animations, platform-specific UI tricks, Focus() calls.
  • ViewModel: what to show (text, lists, flags like IsBusy), what the user can do (commands), simple formatting and validation, calling services.
  • Model / services: HTTP calls, database access, domain rules that would be the same in another UI.

Avoid in a view model: Application.Current.MainPage.DisplayAlert(...), Shell.Current.GoToAsync called directly in dozens of places, and anything with Label, Button or Page. When a view model needs to ask the user something or navigate, give it an interface such as IDialogService or INavigationService that the app implements; the navigation lessons show how.

Code-behind is not forbidden

Code-behind is allowed for pure view concerns: scrolling to a row, starting an animation, handling a gesture that has no command equivalent. The rule is not "zero lines", it is "no application logic in the page".

A common set of view-model members

Most screens need the same few things. A base class often adds:

C#
public abstract class BaseViewModel : ObservableObject
{
    private bool isBusy;
    private string title = "";

    public bool IsBusy
    {
        get => isBusy;
        set { if (SetProperty(ref isBusy, value)) OnPropertyChanged(nameof(IsNotBusy)); }
    }

    public bool IsNotBusy => !IsBusy;

    public string Title { get => title; set => SetProperty(ref title, value); }
}

IsBusy drives an ActivityIndicator and disables buttons during a network call; Title feeds the page title. Do not over-engineer this class; add members only when several view models need them.

MVVM in one picture

View XAML, binds to the view model
ViewModel State and commands, no UI types
Model Data, services, rules

The view never talks to the model directly.

1 / 2

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which statement describes a view model correctly?

    A view model is UI-agnostic. The view binds to its properties and commands and reacts to PropertyChanged.
  2. 2. Why does Name also raise PropertyChanged for Greeting in the example?

    A computed property has no setter to raise the event, so the property it depends on raises it on its behalf.
  3. 3. What is a benefit of MVVM for testing?

    Because the view model does not depend on controls, a unit test can create it, call commands and check properties.
  4. 4. Which belongs in code-behind rather than in the view model?

    Purely visual behaviour that involves controls is a view concern. Calls, rules and data belong in the view model or services.

Summary

  • MVVM separates the view (XAML), the view model (state and commands) and the model (data and services).
  • Views bind to view models; view models never reference the UI.
  • A base class with SetProperty removes INotifyPropertyChanged boilerplate; computed properties need explicit notifications.
  • Code-behind is fine for visual-only work; keep application logic in view models and services.

Next: Commands and the Community Toolkit