.NET MAUI ContentPage
Learn .NET MAUI creating projects
Learn how to create cross-platform applications, thanks to the power of .NET MAUI and a series of real projects.
We are going to analyze the ContentPage page type. This is the most used page type when creating .NET MAUI applications, since they allow to add Layouts and controls to create pages.
Even if we check the default file called MainPage.XAML, we can see that it is a ContentPage:
When you see this type of ContentPage page, it is indicative that it will have Layouts and Controls. In the example code above, the ContentPage has a hierarchy of Layouts and Controls. The first control is a control called ScrollView.
An important point to note with this type of page is that it can only contain one root-level element in its hierarchy.
For example, if we wanted to add a Layout called Grid, which we will see in another lesson, we will see that Visual Studio marks an error indicating that the Content property is being set more than once:
A question you may be asking yourself is, how can we add a new ContentPage to the project?
To do this, we have to right-click on the project, and indicate that we want to create a new element:
This will display a new window, in which we will see different types of pages that we can add.
Let's select the .NET MAUI ContentPage template with a XAML syntax. We have the option to change the name of the page, which I will name ContentPageDemo for this exercise. When clicking on the Add button, the new file named ContentPageDemo.xaml will be created, with its respective associated C# file.
Unlike the initial project, this content page has less content, since the hierarchy has only one StackLayout, and within the StackLayout a Label control:
Once we have created the new ContentPage, let's practice the previous lesson knowledge and assign this new page as the initial page of the project. To do this, we open the App.xaml.cs file, and create a new instance of the ContentPageDemo page by assigning it to MainPage:
MainPage = new ContentPageDemo();
Once we make this change, if we launch the application, we will see the content of the new page being displayed:
As part of the ContentPage, we have a property that we can modify called BackgroundColor, to which we can assign a color to change the background color. Let's assign a default color called DarkBlue for the page, so we will be able to see the change in the emulator:
For the moment, this is all we are going to see about a ContentPage, later on we will work intensively with this type of pages in examples and applications.
If you want to see this tutorial in action, you can play it below: