How to navigate
Hey, you’re back! We’re now done with MVVM and believe me, you did take a big step forward!
Today it will be much simpler, we start the creation of the application main page. But new page also means, enable the user going to that page! So let’s see how to implement the navigation from one page to another.
Navigate to a new page
Let’s start by adding our new page. To do this, right click on the Views folder to add a new file, then choose the template “.NET MAUI ContentPage (C#)” as below. We’ll name this file:
As you will have noticed, the template used to create the page provides us with a default content. So all we have to do now is navigating to this new page!
To do so, go to the file
HomeViewModel.cs and modify the method Enter() as follows:
All that is done here is accessing the navigation service provided by the application in order to display a new page MusicPlayerView.
Actually, when the method PushAsync() is called, the page MusicPlayerView is then added to the very top of the stack of existing pages, exactly as shown in the diagram below:
We’re almost there! For the navigation to work, we need the first page displayed at startup to be included in a NavigationPage.
If you go back to the
App.cs file, there is a method called OnStart() that is automatically executed each time the app is initialized. So modify this method to set HomeView as the application root page, in a NavigationPage:
That’s it, restart the application and click on the Enter button!
Remove the navigation bar
As you will surely have understood, our home page is now contained in a page specially configured for navigation. It therefore contains a navigation bar by default:
From a design point of view, this is not necessarily what you want. So let’s take a quick look at how to remove this header for the home page. Go to the file
HomeView.cs and invoke the method SetHasNavigationBar() in the page constructor, like this:
And now restarting the app, it’s a lot nicer!
The application is slowly coming alive, and even more so with the next chapter! See you soon for the construction of our main page.
More articles in the series: