To create a screen or page (I will use both terms interchangeably) from the code you just have to follow these four steps:
- Create a class named as you want your screen to be called, by convention you must end the name with Page.
- Make that class inherit from the type of page you want to create. The most basic type of page is ContentPage. If you want to see the other types of pages you can read more here.
- In the constructor of the class for your page, instantiate the objects of the controls or views that you want to have inside it. If you are already familiar with XAML, on the code side the control classes are named just like their labels in XAML.
- Assign these controls to the Content or Children property according to the type of page you want to display
After following these steps you will have a page ready to show. To show the page you have several options:
- In the App class constructor (look at the App.cs or App.xaml.cs file) assign the MainPage property with the value of an instance of the page you want to display
- If you want to show it using having a navigation bar on top, you can assign an instance of NavigationPage to the MainPage property and pass it to your page as a parameter. The top bar will show the Title property of your page.
The code would look something like this:
Your project structure:
Some things to take into account:
- The MainPage property of the App class defines the page that is to be displayed first when the application is launched, it can be any object that inherits from the Page class or in other words any type of page.
- When you work in XAML if you look at the
codebehindof your view or screen you will notice the InitializeComponent () method in the constructor. This method creates all the objects that we define in the XAML. In the end, Xamarin .Forms createsthe code view when we work with XAML, only it does it behind the camera.
- Building your views with code is not faster than just using XAML.
- If you have to reference a control from the
codebehindof a XAML you can do it assign it the property x: Name to the control and referencing it using saidname as a local variable from the codebehind.
- The only “
conveniance” of creating the user interface in this way may be that you can apply some logic in the way the UI is formed, having access to the controls since constructing them and such. Say you want to create the UI dynamically based on user input. Other than that I don’t see any need of doing things this way.