Xamarin.Forms - Login Flow APP

Introduction
 
This article demonstrates how to manipulate the navigation stack panel in order to only display the main page of the application once the user has successfully logged in.
 
Let's start.
 
Step 1

Open Visual Studio 2017. Select Templates >> Visual C# >> CrossPlatform.
         
Select CrossPlatform App(Xamarin.Forms or Native) and give the application a suitable name, such as Login_Flow.
        
Now, choose project location and click OK.

 
 
Step 2

Now, create an empty XAML page named SignUpPage.xaml. For that, go to Solution Explorer >> Login_Flow(PCL) >> right-click and select a new item.
 
In the popup window, select Cross platform>>Empty XAML page. Give the page name as SignupPage.xaml. This page is your application signup page.
 
Double-click to get its design View and insert the code given below.

  
  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="Login_Flow.SignupPage">  
  5.     <ContentPage.ToolbarItems>  
  6.         <ToolbarItem Text="LogIn" Clicked="LoginButtonClicked"/>  
  7.     </ContentPage.ToolbarItems>  
  8.       
  9.       
  10.     <ContentPage.Content>  
  11.         <StackLayout>  
  12.             <Label Text="Username"/>  
  13.             <Entry x:Name="UsernameEntry" Placeholder="Username"/>  
  14.             <Label Text="Password"/>  
  15.             <Entry x:Name="PasswordEntry" Placeholder="Password"/>  
  16.             <Label Text=" Email"/>  
  17.             <Entry x:Name="EmailEntry" Placeholder="Email ID"/>  
  18.             <Button Text="SignUp" Clicked="SignUpButtonClicked"/>  
  19.             <Label x:Name="errortext"/>  
  20.         </StackLayout>  
  21.           
  22.           
  23.     </ContentPage.Content>  
  24.       
  25.       
  26.       
  27. </ContentPage>  
Step 3

In this step, open Solution Explorer>>Login_Flow(PCL)>>SignupPage.xaml.cs page and double-click to open design view. Here, the code is given below.

 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6.   
  7. using Xamarin.Forms;  
  8. using Xamarin.Forms.Xaml;  
  9.   
  10. namespace Login_Flow  
  11. {  
  12.     [XamlCompilation(XamlCompilationOptions.Compile)]  
  13.     public partial class SignupPage : ContentPage  
  14.     {  
  15.         public SignupPage()  
  16.         {  
  17.             InitializeComponent();  
  18.         }  
  19.   
  20.         private async void LoginButtonClicked(object sender, EventArgs e)  
  21.         {  
  22.             await Navigation.PushAsync(new LoginPage());  
  23.         }  
  24.   
  25.         async void SignUpButtonClicked(object sender, EventArgs e)  
  26.         {  
  27.             var user = new User  
  28.             {  
  29.                 Username = UsernameEntry.Text,  
  30.                 Password = PasswordEntry.Text,  
  31.                 Email = EmailEntry.Text  
  32.             };  
  33.             var signUpSucceeded = AreDetailsValid(user);  
  34.             if(signUpSucceeded)  
  35.             {  
  36.                 var rootpage = Navigation.NavigationStack.FirstOrDefault();  
  37.                 if (rootpage != null)  
  38.                 {  
  39.                     App.IsUserLoggedIn = true;  
  40.                     Navigation.InsertPageBefore(new MainPage(), Navigation.NavigationStack.First());  
  41.                     await Navigation.PopToRootAsync();  
  42.                 }  
  43.                 else  
  44.                 {  
  45.                     errortext.Text = "SignUpError";  
  46.                 }  
  47.             }  
  48.   
  49.         }  
  50.   
  51.          bool AreDetailsValid(User user)  
  52.         {  
  53.             return (!string.IsNullOrWhiteSpace(user.Username) && !string.IsNullOrWhiteSpace(user.Password) && !string.IsNullOrWhiteSpace(user.Email) && user.Email.Contains("@"));  
  54.         }  
  55.     }  

Step 4

Similarly,  create an empty XAML page LoginPage.Xaml. This page is used for validating the user id and password. Here is the code for this page.This page is your application startup page.

 
  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="Login_Flow.LoginPage"  
  5.              Title="LoginPage">  
  6.     <ContentPage.ToolbarItems>  
  7.         <ToolbarItem Text="SignUp" Clicked="SigUpButtonClicked"/>  
  8.     </ContentPage.ToolbarItems>  
  9.     <ContentPage.Content>  
  10.         <StackLayout>  
  11.             <Label Text="User Name or Email ID"/>  
  12.             <Entry x:Name="UserNameEntry" Placeholder="UserName"/>  
  13.             <Label Text="Password"/>  
  14.             <Entry x:Name="PasswordEntry" IsPassword="True"/>  
  15.             <Button Text="Click to Login" Clicked="Login_Clicked"/>  
  16.             <Label x:Name="LoginFaild"/>  
  17.   
  18.         </StackLayout>  
  19.     </ContentPage.Content>  
  20. </ContentPage>  
Step 5

In this step, go to Solution Explorer>>Login_Flow(PCL)>>LoginPage.xaml.cs page.

 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Linq;  
  5. using System.Runtime.CompilerServices;  
  6. using System.Text;  
  7. using System.Threading.Tasks;  
  8. using System.Windows.Input;  
  9.   
  10. using Xamarin.Forms;  
  11. using Xamarin.Forms.Xaml;  
  12.   
  13. namespace Login_Flow  
  14. {  
  15.   
  16.    // [XamlCompilation(XamlCompilationOptions.Compile)]  
  17.     public partial class LoginPage : ContentPage  
  18.     {  
  19.         public LoginPage()  
  20.         {  
  21.             InitializeComponent();  
  22.            // BindingContext = new ContentPageViewModel();  
  23.         }  
  24.   
  25.         async void SigUpButtonClicked(object sender, EventArgs e)  
  26.         {  
  27.             await Navigation.PushAsync(new SignupPage());  
  28.   
  29.   
  30.         }  
  31.   
  32.         async void Login_Clicked(object sender, EventArgs e)  
  33.         {  
  34.             var user = new User  
  35.             {  
  36.                 Username = UserNameEntry.Text,  
  37.                 Password = PasswordEntry.Text  
  38.             };  
  39.   
  40.             var isVaild = AreCredentialsCorrect(user);  
  41.              if (isVaild)  
  42.                 {  
  43.                     App.IsUserLoggedIn = true;  
  44.                     Navigation.InsertPageBefore(new MainPage(), this);  
  45.                     await Navigation.PopAsync();  
  46.                  }  
  47.              else  
  48.             {  
  49.                 LoginFaild.Text = "InCorrect Password";  
  50.                 PasswordEntry.Text = string.Empty;  
  51.             }  
  52.   
  53.   
  54.         }  
  55.   
  56.          bool AreCredentialsCorrect(User user)  
  57.         {  
  58.             return user.Username == Constants.Username && user.Password == Constants.Password;  
  59.   
  60.         }  
  61.     }  
  62.       
  63.   
  64.      
  65.   
  66.     /* class LoginPageViewModel : INotifyPropertyChanged 
  67.    { 
  68.  
  69.      public LoginPageViewModel() 
  70.        { 
  71.            IncreaseCountCommand = new Command(IncreaseCount); 
  72.        } 
  73.  
  74.        int count; 
  75.  
  76.        string countDisplay = "You clicked 0 times."; 
  77.        public string CountDisplay 
  78.        { 
  79.            get { return countDisplay; } 
  80.            set { countDisplay = value; OnPropertyChanged(); } 
  81.        } 
  82.  
  83.        public ICommand IncreaseCountCommand { get; } 
  84.  
  85.        void IncreaseCount() => 
  86.            CountDisplay = $"You clicked {++count} times"; 
  87.  
  88.  
  89.        public event PropertyChangedEventHandler PropertyChanged; 
  90.        void OnPropertyChanged([CallerMemberName]string propertyName = "") => 
  91.            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));*/  
  92.   
  93. }  
Step 6

Now, click open Solution Explorer>>Login_Flow(PCL)>>MainPage.xaml. This page gets displayed after the user is successfully logged in.

  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.              xmlns:local="clr-namespace:Login_Flow"  
  5.              x:Class="Login_Flow.MainPage">  
  6.   
  7.     <ContentPage.ToolbarItems>  
  8.         <ToolbarItem Text="Logout" Clicked="OnLogout_Clicked" />  
  9.     </ContentPage.ToolbarItems>  
  10.        
  11.       
  12.     <ContentPage.Content>  
  13.         <StackLayout>  
  14.             <Label Text="Main app content goes here"  
  15.                    HorizontalOptions="Center"  
  16.                    VerticalOptions="CenterAndExpand" />  
  17.         </StackLayout>      
  18.     </ContentPage.Content>  
  19.   
  20. </ContentPage>    
Step 7

After this, go to Solution Explorer>>Login_Flow(PCL)>>MainPage.xaml.cs and insert the code given below.

 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using Xamarin.Forms;  
  7.   
  8. namespace Login_Flow  
  9. {  
  10.     public partial class MainPage : ContentPage  
  11.     {  
  12.         public MainPage()  
  13.         {  
  14.             InitializeComponent();  
  15.         }  
  16.   
  17.         async void OnLogout_Clicked(object sender, EventArgs e)  
  18.         {  
  19.   
  20.             App.IsUserLoggedIn = false;  
  21.             Navigation.InsertPageBefore(new LoginPage(), this);  
  22.             await Navigation.PopAsync();  
  23.   
  24.         }  
  25.     }  

Step 8

Afterwards, create a class named User.cs. For that, go to Solution Explorer>>Login_Flow(PCL)>>right click and select a new class.
 
In this popup window, select Cross Platform>>class. Give the class a name like User.
 
Double click to open it and insert the code given below.

 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace Login_Flow  
  8. {  
  9.     class User  
  10.     {  
  11.         public string Username { getset; }  
  12.   
  13.         public string Password { getset; }  
  14.   
  15.         public string Email { getset; }  
  16.     }  
  17. }   
Step 9

Similarly, create another class named Constants.cs.

 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace Login_Flow  
  8. {  
  9.     public static class Constants  
  10.     {  
  11.         public static string Username = "Logesh";  
  12.         public static string Password = "logeshpalani98@";  
  13.     }  
Step 10

After the design view creation, go to Solution Explorer>>Login_Flow(PCL)>>click open App.xaml.cs and declare the MainPage is LoginPage.xaml. If the application is already logged in, the userr is directly navigated to MainPage.xaml. 

 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. using Xamarin.Forms;  
  7.   
  8. namespace Login_Flow  
  9. {  
  10.     public partial class App : Application  
  11.     {  
  12.         public static bool IsUserLoggedIn { getset; }  
  13.         public App()  
  14.         {  
  15.             InitializeComponent();  
  16.             if (!IsUserLoggedIn)  
  17.             {  
  18.                 MainPage = new NavigationPage(new LoginPage());  
  19.             }  
  20.             else  
  21.             {  
  22.                 MainPage = new NavigationPage(new MainPage());  
  23.             }  
  24.         }  
  25.   
  26.         protected override void OnStart()  
  27.         {  
  28.             // Handle when your app starts  
  29.         }  
  30.   
  31.         protected override void OnSleep()  
  32.         {  
  33.             // Handle when your app sleeps  
  34.         }  
  35.   
  36.         protected override void OnResume()  
  37.         {  
  38.             // Handle when your app resumes  
  39.         }  
  40.     }  
  41. }  
Step 11

Now, go to "Build" menu and click "Configure Manager". Here, you can configure your startup projects. Click F5 or Start to build and run your application.

After a few seconds, the app will start running on your Android simulator and you will see your app working successfully.
 
 
 
Click to enter required details and then click SIGNUP button.



You are successfully logged in. By clicking the LOGOUT button, return to the MainPage.xaml.

 

Finally, we have successfully created a Xamarin.Forms Login_Flow Application.

Conclusion

I hope you have learned how to create a Login_Flow application using Visual Studio.

Up Next
    Ebook Download
    View all
    Learn
    View all