Let’s take a quick look at simple navigation (in the next post we’ll look at some more you can do with navigation. As usual, we’ll start with the previous day’s code.
To get started, we’ll add a button to the main page that will take us to the details page. This is a very common paradigm, seen in almost every program sooner or later.
<HorizontalStackLayout>
<Button
Padding="10"
Command="{Binding GetZipCodesCommand}"
IsEnabled="{Binding IsNotBusy}"
Text="Get Zipcodes" />
<Button
Padding="10"
Command="{Binding GoToZipCodeDetailsCommand}"
Text="Go To Details" />
</HorizontalStackLayout>
Note the GoToZipCodeDetailsCommand. We’ll add that to MainViewModel:
[ICommand]
async Task GoToZipCodeDetailsAsync()
{
await Shell.Current.GoToAsync($"ZipCodeDetailsPage", true);
}
Notice the Shell navigation. The boolean decides whether or not there will be navigation.
Our ZipCodeDetailsPage is very simple
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
x:Class="LearningMauiPart10.View.ZipCodeDetailsPage"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
Title="NewPage1">
<VerticalStackLayout>
<Label
HorizontalOptions="Center"
Text="Welcome to .NET MAUI!"/>
<HorizontalStackLayout>
<Label Text="You made it to the details page!" />
</HorizontalStackLayout>
</VerticalStackLayout>
</ContentPage>
And its code behind is equally simple
using LearningMauiPart10.ViewModel;
namespace LearningMauiPart10.View;
public partial class ZipCodeDetailsPage : ContentPage
{
ZipCodeDetailsViewModel viewModel = new();
public ZipCodeDetailsPage()
{
InitializeComponent();
BindingContext = viewModel;
}
}
Finally, for now, ZipCodeDetailsViewModel has nothing to do
using Microsoft.Toolkit.Mvvm.ComponentModel;
namespace LearningMauiPart10.ViewModel;
public partial class ZipCodeDetailsViewModel : ObservableObject
{
public ZipCodeDetailsViewModel()
{
}
}
Registering the route
Navigation in MAUI can be accomplished in two ways
- Traditional Navigation (like in XF)
- Shell-based navigation
We’re going to focus on Shell-based navigation. As you saw above, the way you navigate from MainPage to Details page is to use the shell and what amounts to a URI:
await Shell.Current.GoToAsync($"ZipCodeDetailsPage", true);
To facilitate this we register the route in App.Shell.cs.
public AppShell()
{
InitializeComponent();
Routing.RegisterRoute(nameof(ZipCodeDetailsPage), typeof(ZipCodeDetailsPage));
}
We then add to the Services in MauiProgram.cs
builder.Services.AddSingleton<ZipCodeService>();
builder.Services.AddSingleton<MainViewModel>();
builder.Services.AddSingleton<MainPage>();
builder.Services.AddTransient<ZipCodeDetailsViewModel>();
builder.Services.AddTransient<ZipCodeDetailsPage>();
That’s all it takes. When you press the “Go To Details” button on the main page you are redirected to the details page. There is much you can do with this navigation, and we’ll explore more in upcoming blog posts.
Source code is here.