Learning .NET MAUI – Part 8

Busy week, so this one will be short. I’ve taken the code from Part 7 and copied it into Part 8. The source for 8 is here. So, what’s new?

The most important improvement in 8 is the addition of Community Toolkit for Maui and the Microsoft toolkit for MVVM. Open your “Manage NuGet Packages” window and check that you have or add these packages

  • CommunityToolkit.Maui
  • CommunityToolkit.Maui.Core
  • Microsoft.MauiDependencies
  • Microsoft.Maui.Extensions
  • Microsoft.Toolkit.Mvvm

This allows you to make some magic. The most impressive of which is how much code you will no longer have to write, because the MVVM kit provides code generators. We’ll see a lot more of this as we go, but let’s get started by making some changes.

ObservableObject

The first thing we’ll do is delete ViewModelBase! We won’t need it anymore as we’ll have MainViewModel inherit from ObservableObject. This provides two things: a generic implementation of OnNotifyChanged and also OnNotifyChanging which can be very useful.

ObservableProperty

Look at your ResultList property. Lots of boilerplate code. Delete everything except the backing variable, and just above that add the attribute ObservableProperty

 [ObservableProperty]
 private List<Result> _resultList;

That’s it. The toolkit will generate the property for you. You can work exactly as if you had implemented the property yourself. For example, we can use the (generated) property like this:

ResultList = new List<Result>();

(For those of you who are curious about how this is done, take a look at this article).

Usings and namespaces…

Intellisense will fix up your using statements, but the ones you’ll need so far are

using CommunityToolkit.Maui;
using Microsoft.Toolkit.Mvvm;
using Microsoft.Toolkit.Mvvm.ComponentModel;

Truth is, you only need the last for this example, but you’ll need the others soon.

In the XAML you’ll want to use this namespace

xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"

Your program should continue to work as intended.

More soon.

Caveat Emptor… As noted in the first of this series, I’m learning as I write. I’ll correct things that were initially incorrect, but your mileage may vary.

Comments: The best way to send comments, and especially corrections is to send email to jesseliberty@gmail.com. Thanks!

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen online courses. His latest book, Building APIs with .NET will be released early in 2025. Liberty is a Senior SW Engineer for CNH and he was a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Microsoft MVP.
This entry was posted in Essentials and tagged , . Bookmark the permalink.