Learn About User Settings In Xamarin.Forms

Introduction 

This article will explain how to save specific properties directly to each platform's native setting APIs (NSUserDefaults, SharedPreferences, etc.) using Xam.Plugins.Settings plugin in Xamarin.Forms. This plugin ensures the fastest, most secure, and reliable creation and editing settings per application. Additionally, it works with any Xamarin application, not just Xamarin.Forms.

User Settings In Xamarin

Requirements

  • This article's source code is prepared by using Visual Studio. And it is better to install the latest Visual Studio updates from here.
  • This article is prepared on a MAC machine.
  • This sample project is Xamarin.Forms PCL project.
  • This sample app is targeted for Android, iOS. And, tested for Android & iOS.

Description

Let's start.

Step 1:

First, follow the below steps to create the new Xamarin.Forms project.

  • Open Visual Studio for Mac.
  • Click on the File menu, and select New Solution.
  • In the left pane of the dialog, let's select the type of templates to display. Multiplatform > App > Xamarin.Forms > Blank Forms App and click on Next.
  • Next, enter your app name (Ex: AppSettingsDemo). At the bottom, select target platforms to Android & iOS and shared code to Portable Class Library and click the "Next" button.
  • Then, choose project location with the help of Browse button and click on create.

Now, project structure will be created like below.

  • AppSettingsDemo is for shared code.
  • AppSettingsDemo.Droid is for Android.
  • AppSettingsDemo.iOS is for iOS.

Step 2:

Now, we need to add Xam.Plugins.Settings plugin on all platforms through NuGet.

Right, click on Packages --> AddPackages.

User Settings In Xamarin

Now, search the plugin with the name of Xam.Plugins.Settings, like below.

User Settings In Xamarin

Step 3:

After adding Xam.Plugins.Settings automatically, it will create Helpers folder with Settings.cs class and change the name into UserSettings and we need to declare whatever properties we want to save in App Settings. The below class added 4 fields like UserName, MobileNumber, Email, Password.

UserSettings.cs

  1. // Helpers/Settings.cs  
  2. using Plugin.Settings;  
  3. using Plugin.Settings.Abstractions;  
  4. namespace AppSettingsDemo.Helpers {  
  5.     /// <summary>   
  6.     /// This is the Settings static class that can be used in your Core solution or in any   
  7.     /// of your client applications. All settings are laid out the same exact way with getters   
  8.     /// and setters.     
  9.     /// </summary>   
  10.     public static class UserSettings {  
  11.         static ISettings AppSettings {  
  12.             get {  
  13.                 return CrossSettings.Current;  
  14.             }  
  15.         }  
  16.         public static string UserName {  
  17.             get => AppSettings.GetValueOrDefault(nameof(UserName), string.Empty);  
  18.             set => AppSettings.AddOrUpdateValue(nameof(UserName), value);  
  19.         }  
  20.         public static string MobileNumber {  
  21.             get => AppSettings.GetValueOrDefault(nameof(MobileNumber), string.Empty);  
  22.             set => AppSettings.AddOrUpdateValue(nameof(MobileNumber), value);  
  23.         }  
  24.         public static string Email {  
  25.             get => AppSettings.GetValueOrDefault(nameof(Email), string.Empty);  
  26.             set => AppSettings.AddOrUpdateValue(nameof(Email), value);  
  27.         }  
  28.         public static string Password {  
  29.             get => AppSettings.GetValueOrDefault(nameof(Password), string.Empty);  
  30.             set => AppSettings.AddOrUpdateValue(nameof(Password), value);  
  31.         }  
  32.         public static void ClearAllData() {  
  33.             AppSettings.Clear();  
  34.         }  
  35.     }  
  36. }  

Step 4:

The below View Model will be helpful to store/read string values (UserName, MobileNumber, Email, Password). And we are maintaining common properties for UserLogicViewModel, DetailsPageViewModel by Inheriting BasePageViewModel.

BasePageViewModel.cs

  1. using System.ComponentModel;  
  2. using System.Runtime.CompilerServices;  
  3. using AppSettingsDemo.Helpers;  
  4. using Xamarin.Forms;  
  5. namespace AppSettingsDemo.ViewModels {  
  6.     public class BasePageViewModel: INotifyPropertyChanged {  
  7.         public INavigation _navigation;  
  8.         public string UserName {  
  9.             get => UserSettings.UserName;  
  10.             set {  
  11.                 UserSettings.UserName = value;  
  12.                 NotifyPropertyChanged("UserName");  
  13.             }  
  14.         }  
  15.         public string MobileNumber {  
  16.             get => UserSettings.MobileNumber;  
  17.             set {  
  18.                  UserSettings.MobileNumber = value;  
  19.                 NotifyPropertyChanged("MobileNumber");  
  20.             }  
  21.         }  
  22.         public string Email {  
  23.             get => UserSettings.Email;  
  24.             set {  
  25.                  UserSettings.Email = value;  
  26.                 NotifyPropertyChanged("Email");  
  27.             }  
  28.         }  
  29.         public string Password {  
  30.             get => UserSettings.Password;  
  31.             set {  
  32.                  UserSettings.Password = value;  
  33.                 NotifyPropertyChanged("Password");  
  34.             }  
  35.         }
  36.         #region INotifyPropertyChanged  
  37.         public event PropertyChangedEventHandler PropertyChanged;  
  38.         protected void NotifyPropertyChanged([CallerMemberName] string propertyName = "") {  
  39.             PropertyChanged?.Invoke(thisnew PropertyChangedEventArgs(propertyName));  
  40.         }
  41.         #endregion      
  42.     }  
  43. }  

Step 5:

Create your own XAML page named UserLogin.xaml for user login. And here, we are binding the values like UserName, Mobilenumber, Email, Password from BaseViewModel and LoginCommand is for navigate to DetailsPage.

UserLogin.xaml

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
  3. BackgroundColor="#EEEEEE" 
  4. xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
  5. x:Class="AppSettingsDemo.Views.UserLogin">  
  6.     <ContentPage.Content>  
  7.         <StackLayout Padding="30,80,30,0">  
  8.             <Label Text="User Settings" TextColor="#533F95" FontSize="25" HorizontalOptions="CenterAndExpand" HorizontalTextAlignment="Center" />  
  9.             <StackLayout Spacing="15" VerticalOptions="CenterAndExpand">  
  10.                 <Entry Placeholder="User Name" Text="{Binding UserName}" HorizontalOptions="FillAndExpand" HeightRequest="40" />  
  11.                 <Entry Placeholder="Mobile Number" Keyboard="Numeric" Text="{Binding MobileNumber}" HorizontalOptions="FillAndExpand" HeightRequest="40" />  
  12.                 <Entry Placeholder="Email Address" Keyboard="Email" Text="{Binding Email}" HorizontalOptions="FillAndExpand" HeightRequest="40" />  
  13.                 <Entry Placeholder="Password" IsPassword="true" Text="{Binding Password}" HorizontalOptions="FillAndExpand" HeightRequest="40" />  
  14.                 <Button Text="Login" TextColor="White" BackgroundColor="#533F95" FontAttributes="Bold" BorderColor="White" BorderWidth="0.5" BorderRadius="10" HorizontalOptions="FillAndExpand" Command="{Binding LoginCommand}" /> </StackLayout>  
  15.         </StackLayout>  
  16.     </ContentPage.Content>  
  17. </ContentPage>  

Make BindingContext in code behind with UserLoginPageViewModel.

UserLogin.xaml.cs

  1. using AppSettingsDemo.ViewModels;  
  2. using Xamarin.Forms;  
  3. namespace AppSettingsDemo.Views {  
  4.     public partial class UserLogin: ContentPage {  
  5.         public UserLogin() {  
  6.             InitializeComponent();  
  7.             NavigationPage.SetHasNavigationBar(thisfalse);  
  8.             BindingContext = new UserLoginPageViewModel(Navigation);  
  9.         }  
  10.     }  
  11. }  

The following ViewModel will be helpful to store string values (UserName, Password, MobileNumber) and also for user login.

UserLoginPageViewModel.cs

  1. using System.Windows.Input;  
  2. using Xamarin.Forms;  
  3. namespace AppSettingsDemo.ViewModels {  
  4.     public class UserLoginPageViewModel: BasePageViewModel {  
  5.         public ICommand LoginCommand {  
  6.             get;  
  7.             private set;  
  8.         }  
  9.         public UserLoginPageViewModel(INavigation navigation) {  
  10.             _navigation = navigation;  
  11.             LoginCommand = new Command(() => UpdateUserInfo());  
  12.         }  
  13.         void UpdateUserInfo() {  
  14.             _navigation.PushAsync(new Views.DetailsPage());  
  15.         }  
  16.     }  
  17. }  

Step 6:

Create your own XAML page named DetailsPage.xaml for showing the user login values and also for user logout. And here, we are binding the values from BaseViewModel like UserName, Mobilenumber, Email, Password, LogoutCommand.

DetailsPage.xaml

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
  3. BackgroundColor="#EEEEEE" 
  4. xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
  5. x:Class="AppSettingsDemo.Views.DetailsPage">  
  6.     <ContentPage.Content>  
  7.         <StackLayout Padding="40" Spacing="30">  
  8.             <Label Text="User Details" TextColor="#533F95" FontSize="25" HorizontalOptions="CenterAndExpand" HorizontalTextAlignment="Center" />  
  9.             <StackLayout Spacing="25">  
  10.                 <StackLayout>  
  11.                     <Label Text="User Name:" Font="18" TextColor="Black" HorizontalOptions="FillAndExpand" />  
  12.                     <Label Text="{Binding UserName}" HorizontalOptions="FillAndExpand" TextColor="Gray" /> </StackLayout>  
  13.                 <StackLayout>  
  14.                     <Label Text="Mobile Number:" Font="18" HorizontalOptions="FillAndExpand" TextColor="Black" />  
  15.                     <Label Text="{Binding MobileNumber}" HorizontalOptions="FillAndExpand" TextColor="Gray" /> </StackLayout>  
  16.                 <StackLayout>  
  17.                     <Label Text="Email Address:" Font="18" HorizontalOptions="FillAndExpand" TextColor="Black" />  
  18.                     <Label Text="{Binding Email}" HorizontalOptions="FillAndExpand" TextColor="Gray" /> </StackLayout>  
  19.             </StackLayout>  
  20.             <Button Text="Logout" TextColor="#533F95" BackgroundColor="Transparent" WidthRequest="100" FontAttributes="Bold" BorderColor="#533F95" BorderWidth="1" BorderRadius="10" HorizontalOptions="EndAndExpand" Command="{Binding LogoutCommand}" /> </StackLayout>  
  21.     </ContentPage.Content>  
  22. </ContentPage>  

Make BindingContext in code behind with DetailsPageViewModel.

DetailsPage.xaml.cs

  1. using AppSettingsDemo.ViewModels;  
  2. using Xamarin.Forms;  
  3. namespace AppSettingsDemo.Views {  
  4.     public partial class DetailsPage: ContentPage {  
  5.         public DetailsPage() {  
  6.             InitializeComponent();  
  7.             BindingContext = new DetailsPageViewModel(Navigation);  
  8.         }  
  9.     }  
  10. }  

Below ViewModel will be helpful to read string values (UserName, Password, MobileNumber) from app settings.

DetailsPageViewModel.cs

  1. using System.Windows.Input;  
  2. using AppSettinsDemo.Helpers;  
  3. using AppSettinsDemo.Views;  
  4. using Xamarin.Forms;  
  5. namespace AppSettinsDemo.ViewModels {  
  6.     public class DetailsPageViewModel: BasePageViewModel {  
  7.         public ICommand LogoutCommand {  
  8.             get;  
  9.             private set;  
  10.         }  
  11.         public DetailsPageViewModel(INavigation navigation) {  
  12.             _navigation = navigation;  
  13.             LogoutCommand = new Command(() => ResetUserInfo());  
  14.         }  
  15.         void ResetUserInfo() {  
  16.             _navigation.PushAsync(new UserLogin());  
  17.             UserSettings.ClearAllData();  
  18.         }  
  19.     }  
  20. }  

In LogoutCommand, we are navigating to UserLogin page and calling UserSettings.ClearAllData() it will clear all the data whatever we are storing in app settings.

Output:

User Settings In Xamarin

 User Settings In Xamarin

Please download the sample from here.

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now