.NET MAUI MVVM Tutorials

Welcome to the MVVM Journey

This section guides you through building robust and maintainable cross-platform applications with .NET MAUI using the Model-View-ViewModel (MVVM) architectural pattern.

MVVM promotes separation of concerns, making your code easier to test, understand, and reuse.

Let's get started by setting up your project and understanding the core components.

1. Project Setup

Before diving into MVVM specifics, ensure your .NET MAUI development environment is set up correctly. You'll need the latest .NET SDK and Visual Studio (or VS Code with the MAUI extension).

Prerequisites:

  • .NET 8 SDK (or later)
  • Visual Studio 2022 (17.5+) with .NET MAUI workload

Create a new .NET MAUI project:

dotnet new maui -n MyMvvmApp

For more detailed setup instructions, visit the official MAUI getting started guide.

2. Understanding MVVM Components

The MVVM pattern consists of three main parts:

  • Model: Represents your data and business logic.
  • View: The user interface, typically XAML in .NET MAUI.
  • ViewModel: Acts as an intermediary between the View and the Model. It exposes data from the Model to the View and handles user interactions.

The ViewModel uses data binding to synchronize data between itself and the View.

3. Implementing Your First ViewModel

Let's create a simple ViewModel to manage a counter. We'll use C# for this.

Create a new C# file (e.g., CounterViewModel.cs) in your project's ViewModel folder:

using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.Threading.Tasks;

namespace MyMvvmApp.ViewModels
{
[ObservableObject]
public partial class CounterViewModel
{
[ObservableProperty]
private int _count;

[RelayCommand]
private void IncrementCount()
{
Count++;
}
}
}

Notice the use of CommunityToolkit.Mvvm for automatic property notifications and command generation.

4. Binding ViewModel to the View

Now, let's connect our CounterViewModel to a View. We'll modify the default MainPage.xaml.

First, set the ViewModel as the BindingContext of your page:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:viewmodels="clr-namespace:MyMvvmApp.ViewModels"
x:Class="MyMvvmApp.MainPage"
x:DataType="viewmodels:CounterViewModel">

<!-- ... rest of your page content ... -->
</ContentPage>

Then, bind UI elements to the ViewModel's properties and commands:

<VerticalStackLayout
Spacing="25"
Padding="30"
VerticalOptions="Center">

<!-- Display the count -->
<Label
Text="{Binding Count}"
SemanticProperties.HeadingLevel="Level1"
FontSize="32"
HorizontalOptions="Center" />

<!-- Button to trigger the increment command -->
<Button
Text="Click me"
Command="{Binding IncrementCountCommand}"
HorizontalOptions="Center" />

</VerticalStackLayout>

Next Steps

You've successfully set up a .NET MAUI project and implemented a basic MVVM pattern.

Continue exploring these topics:

Happy coding!