Adding Navigation
So far we have tabbed app with 3 tabs, 2 of which support navigation. Here we are going to make use of MvvmZero
to navigate to a DetailPage
We're going to make use of CommandZero
for our ICommand
implementation, but feel free to use your own if you have a favourite.
We'll start by adding an ICommand
to the SteadyPageVm
that pushes a DetailPageVm
onto the stack.
Replace your SteadyPageVm
with the following:
using FunctionZero.CommandZero;
using FunctionZero.Maui.MvvmZero;
using System.Windows.Input;
namespace MvvmZeroTutorial.Mvvm.PageViewModels
{
public class SteadyPageVm : BasePageVm
{
private readonly IPageServiceZero _pageService;
public ICommand PushDetailPageCommand { get; }
public SteadyPageVm(IPageServiceZero pageService)
{
_pageService = pageService;
PushDetailPageCommand = new CommandBuilder()
.AddGuard(this)
.SetName("Push Detail Page")
.SetExecuteAsync(PushDetailPageExecuteAsync)
.Build();
}
private async Task PushDetailPageExecuteAsync()
{
// Push a page and initialise it with something.
await _pageService.PushVmAsync<DetailPageVm>(vm => vm.Init("Initialise message from SteadyPageVm"));
}
}
}
This is standard MVVM
and should be self explanatory.
In the above code we've chosen to call the Init
method on our DetailsPageVm
each time we push it, so now we'll add the Init
method to the DetailPageVm
, like this:
namespace MvvmZeroTutorial.Mvvm.PageViewModels
{
public class DetailPageVm : BasePageVm
{
private string _helloMessage;
public string HelloMessage { get => _helloMessage;set=>SetProperty(ref _helloMessage, value); }
internal void Init(string helloMessage)
{
HelloMessage = helloMessage;
}
}
}
Now we'll add a Button
to our SteadyPage
and bind it to our new ICommand
Replace the content of SteadyPage.xaml
with the following:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MvvmZeroTutorial.Mvvm.Pages.SteadyPage"
Title="SteadyPage">
<VerticalStackLayout>
<Label Text="Welcome to SteadyPage!" />
<Button Text="{Binding PushDetailPageCommand.Text}" Command="{Binding PushDetailPageCommand}" />
</VerticalStackLayout>
</ContentPage>
Also, we can add a Label
to the DetailPage.xaml
that displays the Init
message passed in when the PageViewModel
was pushed. Modify DetailPage.xaml
like this:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MvvmZeroTutorial.Mvvm.Pages.DetailPage"
Title="DetailPage">
<VerticalStackLayout>
<Label Text="Welcome to DetailPage!" />
<Label Text="{Binding HelloMessage}"/>
</VerticalStackLayout>
</ContentPage>
Do the same with the GoPage
and we have a cross-platform app with a root TabbedPage
and two navigation-stacks.
Last updated