Register your new content
We have our Pages and we have our PageViewModels
Now we will set up the boilerplate startup code so we can present them.
Open MauiProgram.cs and we'll do some initialisation and register our classes.
First we are going to initialise MvvmZero and create a mapping from ViewModel to View. We do this by adding the following UseMvvmZero extension method to the builder method ...
... using statements omitted for brevity ...
public static class MauiProgram
{
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp<App>()
.UseMvvmZero(
serviceBuilder =>
{
serviceBuilder
.MapVmToView<ReadyPageVm, ReadyPage>()
.MapVmToView<SteadyPageVm, SteadyPage>()
.MapVmToView<GoPageVm, GoPage>()
.MapVmToView<DetailPageVm, DetailPage>();
}
)
...This tells MvvmZero the ContentPage to present when we want to present a ViewModel. For example, if we want to present the ReadyPageVm, we will see a ReadyPage whose BindingContext has been set to an instance of ReadyPageVm.
Advanced scenarios are permitted, but this is enough to build any app with standard page-by-page navigation.
MvvmZero(by default) uses the MAUI IoC container, so next we need to register our classes with the container. This is how we do it ...
Pages are added as Singleton if they cannot appear in the view-hierarchy more than once (e.g. they cannot be pushed onto a Navigation Stack more than once. Here we can see everything is Singleton except DetailPage[Vm], because we're going to be pushing these onto distinct Navigation stacks
Note: A common misconception is that using Singleton Pages consumes vast amounts of memory, because after all, a fully realised ContentPage can have a large footprint. In Maui, cross-platform controls are lightweight wrappers around platform controls, and these controls are only instantiated when they are part of the visual tree.
ContentPage can have a large footprint. In Maui, cross-platform controls are lightweight wrappers around platform controls, and these controls are only instantiated when they are part of the visual tree.That's our pre-flight preparation completed, next we'll get things off the ground ...
Last updated