Login Form In Xamarin.Forms For Beginners Using MVVM Pattern

Introduction

 
Today, we will learn how to create a login page in Xamarin.Forms. We also learn to create a login page using the MVVM pattern. We will use Email entry, Password entry, and a button. We also use a command for the login button in the login page.
 
So, let's get started. 
 
Step 1 
 
Open Visual Studio.
 
Click on Create New Project. Go to Installed -> Visual C# -> Cross-Platforms -> Cross-Platform App (Xamarin) and give the project a name XF_Login and project location. 
 
Login Form In Xamarin Forms For Beginner Using MVVM Pattern
Login Form In Xamarin Forms For Beginner Using MVVM Pattern
 
Next, select a blank app, Xamarin.Forms, and .NET Standard options. Then, click OK. 
 
Login Form In Xamarin Forms For Beginner Using MVVM Pattern
 
Step 2 
 
Let's create a new folder in our project.  The View folder is where we will create the Login page: XF_LoginPage.xaml.
 
Go to Solution Explorer -> XF_Login, then right-click to Add -> New Folder, give the name View.
 
Step 3
 
First, we will write the code without ViewModel. Then, we will move to the ViewModel.
 
Select the View folder, right-click, and then click "Add New Item" and select the Content Page template by entering the name XF_LoginPage.xaml. 
 
Now, a page will open with default controls. We will add some controls to take the input.
  1. Email entry for user email
  2. Password entry for user password
  3. A Submit button.
Login Form In Xamarin Forms For Beginner Using MVVM Pattern
 
Login Form In Xamarin Forms For Beginner Using MVVM Pattern
 
Add a field to enter Email using view entry
  1. <Entry x: Name = "Email" Placeholder = "Email"
  2. HeightRequest = "40"    
  3. Keyboard = "Email" />  
Add a field to enter Password using view entry,
  1. <Entry x: Name = "Password" Placeholder = "Password"      
  2.                             HeightRequest = "40"      
  3.                            IsPassword = "True"/>    
Add a Login button
  1. <Button x:Name= "loginbtn" Text = "Login " Clicked="Loginbtn_Clicked"   
  2.  FontAttributes = "Bold" FontSize = "Large" HorizontalOptions = "FillAndExpand"    
  3.  BackgroundColor = "# 088da5" />  
Now, add another page in the View folder by entering the name as WelcomePage, and write the following code.
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"  
  3.              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"  
  4.              x:Class="XF_Login.View.WelcomPage"  
  5.              Title="Welcom Page"  
  6.              NavigationPage.HasBackButton="False">  
  7.     <ContentPage.Content>  
  8.         <StackLayout>  
  9.             <Label Text="Welcome to Xamarin.Forms!"  
  10.                 VerticalOptions="CenterAndExpand"   
  11.                 HorizontalOptions="CenterAndExpand" />  
  12.         </StackLayout>  
  13.     </ContentPage.Content>  
  14. </ContentPage>  
Now we write logic for login button click event in code-behind file XF_LoginPage.xaml.cs 
  1. private void Loginbtn_Clicked(object sender, EventArgs e)  
  2.        {  
  3.            //null or empty field validation, check weather email and password is null or empty  
  4.            if (string.IsNullOrEmpty(Email.Text) || string.IsNullOrEmpty(Password.Text))  
  5.                DisplayAlert("Empty Values""Please enter Email and Password""OK");  
  6.            else  
  7.            {  
  8.                if (Email.Text == "[email protected]" && Password.Text == "1234")  
  9.                {  
  10.                    DisplayAlert("Login Success""""Ok");  
  11.                    //Navigate to Wellcom page after successfully login  
  12.                    Navigation.PushAsync(new WelcomPage());   
  13.                }  
  14.                else  
  15.                    DisplayAlert("Login Fail""Please enter correct Email and Password""OK");  
  16.            }  
  17.        }  
And finally open App.xml.cs under the project XF_Login ->App.xml ->App.xml.cs
 
Login Form In Xamarin Forms For Beginner Using MVVM Pattern
 
Set Navigation page as Main Page in constrctor and pass the XF_LoginPage().
  1. using Xamarin.Forms;  
  2. using Xamarin.Forms.Xaml;  
  3. using XF_Login.View;  
  4.   
  5. [assembly: XamlCompilation(XamlCompilationOptions.Compile)]  
  6. namespace XF_Login  
  7. {  
  8.     public partial class App : Application  
  9.     {  
  10.         public App()  
  11.         {  
  12.             InitializeComponent();  
  13.             //set main page as navigation page   
  14.             MainPage = new NavigationPage(new XF_LoginPage());  
  15.         }  
  16.   
  17.         protected override void OnStart()  
  18.         {  
  19.             // Handle when your app starts  
  20.         }  
  21.   
  22.         protected override void OnSleep()  
  23.         {  
  24.             // Handle when your app sleeps  
  25.         }  
  26.   
  27.         protected override void OnResume()  
  28.         {  
  29.             // Handle when your app resumes  
  30.         }  
  31.     }  
  32. }  
And that's it. Now run your project and see the output.
 
Step 4 
 
Now create the other folder named as ViewModels, just like Views folder 
 
For View Model, we will make little changes in our code.
  1. We will create a new class for the login view model
  2. Set binding for each control or field
Right-click the ViewModels folder and select Add ->Class. This opens a new dialog box.Give a name to LoginViewModel.cs
 
Open LoginViewModel.cs file and give the following code.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Text;  
  5. using System.Windows.Input;  
  6. using Xamarin.Forms;  
  7. using XF_Login.View;  
  8.   
  9. namespace XF_Login.ViewModel  
  10. {  
  11.     public class LoginViewModel : INotifyPropertyChanged  
  12.     {  
  13.         public event PropertyChangedEventHandler PropertyChanged;  
  14.         public LoginViewModel()  
  15.         {  
  16.   
  17.         }  
  18.         private string email;  
  19.         public string Email  
  20.         {  
  21.             get { return email; }  
  22.             set  
  23.             {  
  24.                 email = value;  
  25.                 PropertyChanged(thisnew PropertyChangedEventArgs("Email"));  
  26.             }  
  27.         }  
  28.         private string password;  
  29.         public string Password  
  30.         {  
  31.             get { return password; }  
  32.             set  
  33.             {  
  34.                 password = value;  
  35.                 PropertyChanged(thisnew PropertyChangedEventArgs("Password"));  
  36.             }  
  37.         }  
  38.         public Command LoginCommand  
  39.         {  
  40.             get  
  41.             {  
  42.                 return new Command(Login);  
  43.             }  
  44.         }  
  45.   
  46.         private void Login()  
  47.         {  
  48.             //null or empty field validation, check weather email and password is null or empty  
  49.             if (string.IsNullOrEmpty(Email) || string.IsNullOrEmpty(Password))  
  50.               App.Current.MainPage.DisplayAlert("Empty Values""Please enter Email and Password""OK");  
  51.             else  
  52.             {  
  53.                 if (Email == "[email protected]" && Password == "1234")  
  54.                 {  
  55.                   App.Current.MainPage.DisplayAlert("Login Success""""Ok");  
  56.                     //Navigate to Wellcom page after successfully login  
  57.                     App.Current.MainPage.Navigation.PushAsync(new WelcomPage());  
  58.                 }  
  59.                 else  
  60.                   App.Current.MainPage.DisplayAlert("Login Fail""Please enter correct Email and Password""OK");  
  61.             }  
  62.         }  
  63.     }  
  64. }  
In this code, we created the following properties: Email, Password, and the command LoginCommand that we will use in the Login button on the Login page.
 
I am not using a database to validate the Email and Password; for simplicity, I'm doing a very simple code validation.
 
The LoginViewModel class implements the INotifyPropertyChanged interface so that the changes made to properties are notified to Views.
 
Now, we need to make some changes in our login page
 
Step 5
 
Open the LoginPage.xml and write the following code.
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"  
  3.              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"  
  4.              x:Class="XF_Login.View.XF_LoginPage">  
  5.     <ContentPage.Content>  
  6.         <StackLayout>  
  7.             <Entry x:Name = "Email" Placeholder = "Email" Text="{Binding Email}"  
  8.                    HeightRequest = "40"  
  9.                    Keyboard = "Email"/>  
  10.             <Entry x:Name = "Password" Text="{Binding Password}" Placeholder = "Password"  
  11.                    HeightRequest = "40"  
  12.                    IsPassword = "True"/>  
  13.             <Button x:Name= "loginbtn" Text = "Login "   
  14.                     Command="{Binding LoginCommand}"  
  15.                     HorizontalOptions = "FillAndExpand"/>  
  16.         </StackLayout>  
  17.     </ContentPage.Content>  
  18. </ContentPage>  
We are using databinding to bind the value of the Views used with the Email, Password, and LoginCommand properties defined in LoginViewModel.

But how will our View communicate with ViewModel?
 
Step 6 
 
We do this in the code-behind file LoginPage.xaml.cs by setting the following code. 
  1. using System;  
  2. using Xamarin.Forms;  
  3. using Xamarin.Forms.Xaml;  
  4. using XF_Login.ViewModel;  
  5.   
  6. namespace XF_Login.View  
  7. {  
  8.     [XamlCompilation(XamlCompilationOptions.Compile)]  
  9.     public partial class XF_LoginPage : ContentPage  
  10.     {  
  11.         LoginViewModel loginViewModel;  
  12.         public XF_LoginPage ()  
  13.         {  
  14.             loginViewModel = new LoginViewModel();   
  15.             InitializeComponent ();  
  16.             BindingContext = loginViewModel;  
  17.         }  
  18.     }  
  19. }  
In this code, we are creating an instance of LoginViewModel and doing the binding with our View using the BindingContext property.
 
And that's it. We are done. We have successfully created a login page using the MVVM pattern.
 
Running the project, we will get the following result in the emulator for Android.
 
Login Form In Xamarin Forms For Beginner Using MVVM Pattern   Login Form In Xamarin Forms For Beginner Using MVVM Pattern
Login Form In Xamarin Forms For Beginner Using MVVM Pattern  Login Form In Xamarin Forms For Beginner Using MVVM Pattern
 


Similar Articles