Skip to content

Create New Page

Bader Albarrak edited this page Jul 31, 2020 · 5 revisions

Steps

In order to create a new page and follow MVVM Design Pattern.

You have to do 4 things

  • Create ContentPage and make sure it inherit from 'BaseContentPage`
  • Create ViewModel for that page and make sure it inherited from BaseViewModel
  • Add DI for the ViewModel
  • Map ContentPage with ViewModel you have created

Example

Lets assume we want to create a ContentPage with a name LoginPage

  • Create a new ContentPage under the Views Folder and name it LoginPage
  • Modify the code behind of the page and make it inherit from BaseContentPage page like below code
public partial class LoginPage : BaseContentPage
{
    public LoginPage()
    {
      InitializeComponent();
    }
}
  • Modify the xaml of the page by adding local namespace as the followings
<local:BaseContentPage
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:local="clr-namespace:XamarinAppTemplate"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:d="http://xamarin.com/schemas/2014/forms/design"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Title="Login Page"
    x:Class="XamarinAppTemplate.Views.LoginPage">
</local:BaseContentPage>
  • Create a new class called LoginViewModel under the folder ViewModels and make sure it inherited from BaseViewModel as followings
public class LoginViewModel : BaseViewModel
{
   public LoginViewModel()
   {

   }
}
  • Add DI for the view model by modify the method ConfigureServices in Startup.cs under folder Configurations like below
serviceCollections.AddTransient<LoginViewModel>();
  • Map the page to the view model by modify the method RegisterRoutes() in NavigationService.cs under the folder Services to be like below
XamarinAppTemplateRoute.Register(typeof(LoginViewModel), typeof(LoginPage));

Note: the name maybe different based on your project name

Now all sets and the page is ready to be navigated to

From any ViewModel you can navigate to the page by calling await _navService.GoToAsync<LoginViewModel>();

Clone this wiki locally