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.
Next, select a blank app, Xamarin.Forms, and .NET Standard options. Then, click OK.
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.
- Email entry for user email
- Password entry for user password
- A Submit button.
Add a field to enter Email using view entry
- <Entry x: Name = "Email" Placeholder = "Email"
- HeightRequest = "40"
- Keyboard = "Email" />
Add a field to enter Password using view entry,
- <Entry x: Name = "Password" Placeholder = "Password"
- HeightRequest = "40"
- IsPassword = "True"/>
Add a Login button
- <Button x:Name= "loginbtn" Text = "Login " Clicked="Loginbtn_Clicked"
- FontAttributes = "Bold" FontSize = "Large" HorizontalOptions = "FillAndExpand"
- BackgroundColor = "# 088da5" />
Now, add another page in the View folder by entering the name as WelcomePage, and write the following code.
- <?xml version="1.0" encoding="utf-8" ?>
- <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
- xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
- x:Class="XF_Login.View.WelcomPage"
- Title="Welcom Page"
- NavigationPage.HasBackButton="False">
- <ContentPage.Content>
- <StackLayout>
- <Label Text="Welcome to Xamarin.Forms!"
- VerticalOptions="CenterAndExpand"
- HorizontalOptions="CenterAndExpand" />
- </StackLayout>
- </ContentPage.Content>
- </ContentPage>
Now we write logic for login button click event in code-behind file XF_LoginPage.xaml.cs
- private void Loginbtn_Clicked(object sender, EventArgs e)
- {
-
- if (string.IsNullOrEmpty(Email.Text) || string.IsNullOrEmpty(Password.Text))
- DisplayAlert("Empty Values", "Please enter Email and Password", "OK");
- else
- {
- if (Email.Text == "[email protected]" && Password.Text == "1234")
- {
- DisplayAlert("Login Success", "", "Ok");
-
- Navigation.PushAsync(new WelcomPage());
- }
- else
- DisplayAlert("Login Fail", "Please enter correct Email and Password", "OK");
- }
- }
And finally open App.xml.cs under the project XF_Login ->App.xml ->App.xml.cs
Set Navigation page as Main Page in constrctor and pass the XF_LoginPage().
- using Xamarin.Forms;
- using Xamarin.Forms.Xaml;
- using XF_Login.View;
-
- [assembly: XamlCompilation(XamlCompilationOptions.Compile)]
- namespace XF_Login
- {
- public partial class App : Application
- {
- public App()
- {
- InitializeComponent();
-
- MainPage = new NavigationPage(new XF_LoginPage());
- }
-
- protected override void OnStart()
- {
-
- }
-
- protected override void OnSleep()
- {
-
- }
-
- protected override void OnResume()
- {
-
- }
- }
- }
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.
- We will create a new class for the login view model
- 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.
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Text;
- using System.Windows.Input;
- using Xamarin.Forms;
- using XF_Login.View;
-
- namespace XF_Login.ViewModel
- {
- public class LoginViewModel : INotifyPropertyChanged
- {
- public event PropertyChangedEventHandler PropertyChanged;
- public LoginViewModel()
- {
-
- }
- private string email;
- public string Email
- {
- get { return email; }
- set
- {
- email = value;
- PropertyChanged(this, new PropertyChangedEventArgs("Email"));
- }
- }
- private string password;
- public string Password
- {
- get { return password; }
- set
- {
- password = value;
- PropertyChanged(this, new PropertyChangedEventArgs("Password"));
- }
- }
- public Command LoginCommand
- {
- get
- {
- return new Command(Login);
- }
- }
-
- private void Login()
- {
-
- if (string.IsNullOrEmpty(Email) || string.IsNullOrEmpty(Password))
- App.Current.MainPage.DisplayAlert("Empty Values", "Please enter Email and Password", "OK");
- else
- {
- if (Email == "[email protected]" && Password == "1234")
- {
- App.Current.MainPage.DisplayAlert("Login Success", "", "Ok");
-
- App.Current.MainPage.Navigation.PushAsync(new WelcomPage());
- }
- else
- App.Current.MainPage.DisplayAlert("Login Fail", "Please enter correct Email and Password", "OK");
- }
- }
- }
- }
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.
- <?xml version="1.0" encoding="utf-8" ?>
- <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
- xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
- x:Class="XF_Login.View.XF_LoginPage">
- <ContentPage.Content>
- <StackLayout>
- <Entry x:Name = "Email" Placeholder = "Email" Text="{Binding Email}"
- HeightRequest = "40"
- Keyboard = "Email"/>
- <Entry x:Name = "Password" Text="{Binding Password}" Placeholder = "Password"
- HeightRequest = "40"
- IsPassword = "True"/>
- <Button x:Name= "loginbtn" Text = "Login "
- Command="{Binding LoginCommand}"
- HorizontalOptions = "FillAndExpand"/>
- </StackLayout>
- </ContentPage.Content>
- </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.
- using System;
- using Xamarin.Forms;
- using Xamarin.Forms.Xaml;
- using XF_Login.ViewModel;
-
- namespace XF_Login.View
- {
- [XamlCompilation(XamlCompilationOptions.Compile)]
- public partial class XF_LoginPage : ContentPage
- {
- LoginViewModel loginViewModel;
- public XF_LoginPage ()
- {
- loginViewModel = new LoginViewModel();
- InitializeComponent ();
- BindingContext = loginViewModel;
- }
- }
- }
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.