Xamarin.Forms MVVM - How To Fetch Mobile Contacts

Introduction 

In this article we are going to learn how to fetch mobile contacts in our app and how we can select specific contacts from ContactList with the help of checkbox.

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

Description

This article will explain the below topics,

  1. How to create Xamarin.Forms PCL project with Visual Studio for Mac
  2. How to add Components to the Xamarin.Forms App
  3. How to get mobile contacts using Xamarin.Mobile in Xamarin.Forms
  4. How to create CheckBox for selecting multiple contacts from contacts list
  5. How to bind contact list to the UI
  6. How to change the NavigationBar Background and TextColor
1) How to create Xamarin.Forms PCL project with Visual Studio for Mac?

The creation of a Xamarin.Forms project is very simple in Visual Studio for Mac. It will create three projects,

  • Shared Code
  • Android
  • iOS

The Mac system with Visual Studio for Mac doesn't support Windows projects (UWP, Windows, Windows Phone).

The following steps will show you how to create Xamarin.Forms projects on a Mac system using Visual Studio.

First, open Visual Studio for Mac. Then click on New Project.

Xamarin

After that, we need to select whether you're doing Xamarin.Forms or Xamarin.Android or Xamarin.iOS project. If we want to create Xamarin.Forms project, just follow the below screenshot.

Xamarin

Then, we have to give the app name; i.e., GetContactsDemo.

Xamarin

Note

In the above screen, under Shared Code, select Portable Class Library or use Shared Library.

Then, click on Next button and the following screenshot will be displayed. In that screen, we have to browse the file path where we want to save that application on our PC.

Xamarin

After clicking on the create button it will create the GetContactsDemo Xamarin.Forms project like below.

Xamarin

And the project structure will be,

  • GetContactsDemo
    It is for Shared Code

  • GetContactsDemo.Droid
    It is for Android.

  • GetContactsDemo.iOS
    It is for iOS
Xamarin 
 
2) How to add Components to the Xamarin.Forms App?

Now we are installing  Xamarin.Mobile component on Xamarin.Android and Xamarin.iOS projects for getting mobile contacts.

Step 1:

First Right Click on Components folder and click on get more Components.

Xamarin

Step 2:

In right side SearchBox, search for "Xamarin.Mobile", we can get the Xamarin.Mobile component right side panel. Double click on component to install on our app.

Xamarin

Step 3:

In components folder we can check whether Xamarin.Mobile component added or not.

Xamarin
 
3) How to get mobile contacts using Xamarin.Mobile in Xamarin.Forms?

Portable Class Library(PCL):

Create an interface IContactService inside the DependencyServices folder and having method declaration of GetAllContacts.

IContactService.cs

  1. using System.Collections.Generic;  
  2. using System.Threading.Tasks;  
  3. using GetContactsDemo.Models;  
  4. namespace GetContactsDemo.DependencyServices {  
  5.     public interface IContactService {  
  6.         Task<IEnumerable<ContactDetails>> GetAllContacts();  
  7.     }  
  8. }  

Xamarin.Android

First we need to add permissions in Manifest file for accessing contacts.

AndroidManifest.xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.NavigateToLocation.GetContactsDemo">  
  3.     <uses-sdk android:minSdkVersion="15" />  
  4.     <uses-permission android:name="android.permission.READ_CONTACTS" />  
  5.     <application android:label="GetContactsDemo"> </application>  
  6. </manifest>  

Create a class ContactService and need to implement GetAllContacts method like below.

ContactService.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Threading.Tasks;  
  4. using Xamarin.Forms;  
  5. using System.Linq;  
  6. using GetContactsDemo.Droid;  
  7. using GetContactsDemo.DependencyServices;  
  8. using GetContactsDemo.Models;  
  9. [assembly: Dependency(typeof(ContactService))]  
  10. namespace GetContactsDemo.Droid {  
  11.     public class ContactService: IContactService {  
  12.         readonly Xamarin.Contacts.AddressBook _addressBook;  
  13.         static IEnumerable<ContactDetails> _contactsList;  
  14.         public ContactService() {  
  15.             _addressBook = new Xamarin.Contacts.AddressBook(Forms.Context.ApplicationContext);  
  16.         }  
  17.         public async Task<IEnumerable<ContactDetails>> GetAllContacts() {  
  18.             var contacts = new List<ContactDetails>();  
  19.             await _addressBook.RequestPermission().ContinueWith(t => {  
  20.                 if (!t.Result) {  
  21.                     App.Current.MainPage.DisplayAlert("GetContactsDemo""Sorry ! Permission was denied""Ok");  
  22.                     return;  
  23.                 }  
  24.                 foreach(var contact inToList()) {  
  25.                    contacts.Add(new ContactDetails() {  
  26.                         FirstName = contact.FirstName != null ? contact.FirstName : string.Empty,  
  27.                             LastName = contact.LastName != null ? contact.LastName : string.Empty,  
  28.                             DisplayName = contact.DisplayName != null ? contact.DisplayName : string.Empty,  
  29.                             EmailId = contact.Emails.FirstOrDefault() != null ? contact.Emails.FirstOrDefault().Address : String.Empty,  
  30.                             Number = contact.Phones.FirstOrDefault() != null ? contact.Phones.FirstOrDefault().Number : String.Empty,  
  31.                             IsVisible = false  
  32.                     });  
  33.                 }  
  34.             });  
  35.             _contactsList = (from c in contacts orderby c.FirstName select c).ToList();  
  36.             return _contactsList;  
  37.         }  
  38.     }  
  39. }  

Xamarin.iOS

Giving permissions in info.plist file for accessing contacts.

info.plist

Key     :   Privacy - Contacts Usage Description    

Value  :  Access Contacts(It's anything)

Xamarin

Now Create a class ContactService and need to implement GetAllContacts method like below.

ContactService.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using GetContactsDemo.iOS;  
  6. using GetContactsDemo.DependencyServices;  
  7. using GetContactsDemo.Models;  
  8. [assembly: Xamarin.Forms.Dependency(typeof(ContactService))]  
  9. namespace GetContactsDemo.iOS {  
  10.     public class ContactService: IContactService {  
  11.         private readonlyContacts.AddressBook _addressBook;  
  12.         private static IEnumerable < ContactDetails > _contactsList;  
  13.         public ContactService() {  
  14.             _addressBook = new Xamarin.Contacts.AddressBook();  
  15.         }  
  16.         public async Task<IEnumerable<ContactDetails>> GetAllContacts() {  
  17.             var contacts = new List<ContactDetails>();  
  18.             await _addressBook.RequestPermission().ContinueWith(t => {  
  19.                 if (!t.Result) {  
  20.                     App.Current.MainPage.DisplayAlert("GetContactsDemo""Sorry ! Permission was denied""Ok");  
  21.                     return;  
  22.                 }  
  23.                 foreach(var contact inToList()) {  
  24.                     contacts.Add(new ContactDetails() {  
  25.                         FirstName = contact.FirstName != null ? contact.FirstName : string.Empty,  
  26.                             LastName = contact.LastName != null ? contact.LastName : string.Empty,  
  27.                             DisplayName = contact.DisplayName != null ? contact.DisplayName : string.Empty,  
  28.                             EmailId = contact.Emails.FirstOrDefault() != null ? contact.Emails.FirstOrDefault().Address : String.Empty,  
  29.                             Number = contact.Phones.FirstOrDefault() != null ? contact.Phones.FirstOrDefault().Number : String.Empty,  
  30.                             IsVisible = false //for checkbox visible   
  31.                     });  
  32.                 }  
  33.             });  
  34.             _contactsList = (from c in contacts orderby c.FirstName select c).ToList();  
  35.             return _contactsList;  
  36.         }  
  37.     }  
  38. }  

4) How to create CheckBox for selecting multiple contacts from contacts list?

Portable Class Library(PCL)

Now we are creating checkbox control to select multiple contacts from contact list.

Create  folder with the name CustomControls and after that right click on your newly created folder => Add => New File => Forms => Forms ContentView Xaml and name it CheckBox.

Xamarin

CheckBox.xaml

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <ContentView xmlns="http://xamarin.com/schemas/2014/forms" 
  3. xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
  4. x:Class="GetContactsDemo.CustomControls.CheckBox">  
  5.     <ContentView.Content>  
  6.         <StackLayout Orientation="Horizontal" x:Name="mainContainer" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" Padding="0" Spacing="5">  
  7.             <AbsoluteLayout HorizontalOptions="Center" VerticalOptions="Center" WidthRequest="20" HeightRequest="20" x:Name="imageContainer">  
  8.                 <Image Source="{Binding CheckedBackgroundImageSource}" x:Name="checkedBackground" Aspect="AspectFit" LayoutBounds="0.5, 0.5, 1, 1" LayoutFlags="All" Opacity="0" InputTransparent="True" />  
  9.                 <Image Source="{Binding BorderImageSource}" x:Name="borderImage" Aspect="AspectFit" LayoutBounds="0.5, 0.5, 1, 1" LayoutFlags="All" InputTransparent="True" />  
  10.                 <Image Source="{Binding CheckmarkImageSource}" x:Name="checkedImage" Aspect="AspectFit" LayoutBounds="0.5, 0.5, 1, 1" LayoutFlags="All" Opacity="0" InputTransparent="True" /> 
  11.        </AbsoluteLayout>  
  12.             <Label x:Name="controlLabel" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" HorizontalTextAlignment="Start" VerticalTextAlignment="Center" Text="{Binding Title}" Style="{Binding LabelStyle}" InputTransparent="True" /> 
  13.       </StackLayout>  
  14.     </ContentView.Content>  
  15. </ContentView>  

Now add the below Bindable properties for our CheckBox control in code behind and animation properties.

  • TitleProperty: To bind tile of check box.
  • LabelStyleProperty: To to set style to Title label.
  • IsCheckedProperty: To maintain CheckBox states for check or uncheck.
  • BorderImageSourceProperty: To set Border image for CheckBox.
  • CheckedBackgroundImageSourceProperty:To set Background image for CheckBox.
  • CheckMarkImageSourceProperty: To set CheckMark image for CheckBox.
  • CheckedChangedCommandProperty: To make interaction with checkbox when user tap on it's main container.

CheckBox.xaml.cs

  1. using Xamarin.Forms;  
  2. using Xamarin.Forms.Xaml;  
  3. namespace GetContactsDemo.CustomControls {  
  4.     [XamlCompilation(XamlCompilationOptions.Compile)]  
  5.     public partial class CheckBox: ContentView {  
  6.         public CheckBox() {  
  7.             InitializeComponent();  
  8.             controlLabel.BindingContext = this;  
  9.             checkedBackgroundColor.BindingContext = this;  
  10.             checkedImage.BindingContext = this;  
  11.             borderImage.BindingContext = this;  
  12.             mainContainer.GestureRecognizers.Add(new TapGestureRecognizer() {  
  13.                 Command = new Command(tapped)  
  14.             });  
  15.         }  
  16.         public static readonly BindableProperty BorderImageSourceProperty = BindableProperty.Create(nameof(BorderImageSource), typeof(string), typeof(CheckBox), "", BindingMode.OneWay);  
  17.         public static readonly BindableProperty CheckedBackgroundImageSourceProperty = BindableProperty.Create(nameof(CheckedBackgroundImageSource), typeof(string), typeof(CheckBox), "", BindingMode.OneWay);  
  18.         public static readonly BindableProperty CheckmarkImageSourceProperty = BindableProperty.Create(nameof(CheckmarkImageSource), typeof(string), typeof(CheckBox), "", BindingMode.OneWay);  
  19.         public static readonly BindableProperty IsCheckedProperty = BindableProperty.Create(nameof(IsChecked), typeof(bool), typeof(CheckBox), false, BindingMode.TwoWay, propertyChanged: checkedPropertyChanged);  
  20.         public static readonly BindableProperty TitleProperty = BindableProperty.Create(nameof(Title), typeof(string), typeof(CheckBox), "", BindingMode.OneWay);  
  21.         public static readonly BindableProperty CheckedChangedCommandProperty = BindableProperty.Create(nameof(CheckedChangedCommand), typeof(Command), typeof(CheckBox), null, BindingMode.OneWay);  
  22.         public static readonly BindableProperty LabelStyleProperty = BindableProperty.Create(nameof(LabelStyle), typeof(Style), typeof(CheckBox), null, BindingMode.OneWay);  
  23.         public string BorderImageSource {  
  24.             get {  
  25.                 return (string) GetValue(BorderImageSourceProperty);  
  26.             }  
  27.             set {  
  28.                 SetValue(BorderImageSourceProperty, value);  
  29.             }  
  30.         }  
  31.         public string CheckedBackgroundImageSource {  
  32.             get {  
  33.                 return (string) GetValue(CheckedBackgroundImageSourceProperty);  
  34.             }  
  35.             set {  
  36.                 SetValue(CheckedBackgroundImageSourceProperty, value);  
  37.             }  
  38.         }  
  39.         public string CheckmarkImageSource {  
  40.             get {  
  41.                 return (string) GetValue(CheckmarkImageSourceProperty);  
  42.             }  
  43.             set {  
  44.                 SetValue(CheckmarkImageSourceProperty, value);  
  45.             }  
  46.         }  
  47.         public bool IsChecked {  
  48.             get {  
  49.                 return (bool) GetValue(IsCheckedProperty);  
  50.             }  
  51.             set {  
  52.                 SetValue(IsCheckedProperty, value);  
  53.             }  
  54.         }  
  55.         public string Title {  
  56.             get {  
  57.                 return (string) GetValue(TitleProperty);  
  58.             }  
  59.             set {  
  60.                 SetValue(TitleProperty, value);  
  61.             }  
  62.         }  
  63.         public Command CheckedChangedCommand {  
  64.             get {  
  65.                 return (Command) GetValue(CheckedChangedCommandProperty);  
  66.             }  
  67.             set {  
  68.                 SetValue(CheckedChangedCommandProperty, value);  
  69.             }  
  70.         }  
  71.         public Style LabelStyle {  
  72.             get {  
  73.                 return (Style) GetValue(LabelStyleProperty);  
  74.             }  
  75.             set {  
  76.                 SetValue(LabelStyleProperty, value);  
  77.             }  
  78.         }  
  79.         public Label ControlLabel {  
  80.             get {  
  81.                 return controlLabel;  
  82.             }  
  83.         }  
  84.         static void checkedPropertyChanged(BindableObject bindable, object oldValue, object newValue) {  
  85.             ((CheckBox) bindable).ApplyCheckedState();  
  86.         }  
  87.         /// <summary>      
  88.         /// Handle chackox tapped action      
  89.         /// </summary>      
  90.         void tapped() {  
  91.             IsChecked = !IsChecked;  
  92.             ApplyCheckedState();  
  93.         }  
  94.         /// <summary>      
  95.         /// Reflect the checked event change on the UI      
  96.         /// with a small animation      
  97.         /// </summary>      
  98.         /// <param name="isChecked"></param>      
  99.         ///       
  100.         void ApplyCheckedState() {  
  101.             Animation storyboard = new Animation();  
  102.             Animation fadeAnim = null;  
  103.             Animation checkBounceAnim = null;  
  104.             Animation checkFadeAnim = null;  
  105.             double fadeStartVal = 0;  
  106.             double fadeEndVal = 1;  
  107.             double scaleStartVal = 0;  
  108.             double scaleEndVal = 1;  
  109.             Easing checkEasing = Easing.CubicIn;  
  110.             if (IsChecked) {  
  111.                 checkedImage.Scale = 0;  
  112.                 fadeStartVal = 0;  
  113.                 fadeEndVal = 1;  
  114.                 scaleStartVal = 0;  
  115.                 scaleEndVal = 1;  
  116.                 checkEasing = Easing.CubicIn;  
  117.             } else {  
  118.                 fadeStartVal = 1;  
  119.                 fadeEndVal = 0;  
  120.                 scaleStartVal = 1;  
  121.                 scaleEndVal = 0;  
  122.                 checkEasing = Easing.CubicOut;  
  123.             }  
  124.             fadeAnim = new Animation(callback: d => checkedBackground.Opacity = d, 
  125.                                      start: fadeStartVal, 
  126.                                      end: fadeEndVal, 
  127.                                      easing: Easing.CubicOut);  
  128.             checkFadeAnim = new Animation(callback: d => checkedImage.Opacity = d, 
  129.                                           start: fadeStartVal, 
  130.                                           end: fadeEndVal, 
  131.                                           easing: checkEasing);  
  132.             checkBounceAnim = new Animation(callback: d => checkedImage.Scale = d, 
  133.                                             start: scaleStartVal, 
  134.                                             end: scaleEndVal, 
  135.                                             easing: checkEasing);  
  136.             storyboard.Add(0, 0.6, fadeAnim);  
  137.             storyboard.Add(0, 0.6, checkFadeAnim);  
  138.             storyboard.Add(0.4, 1, checkBounceAnim);  
  139.             storyboard.Commit(this"checkAnimation", length: 600);  
  140.             if (CheckedChangedCommand != null && CheckedChangedCommand.CanExecute(this))  
  141.                   CheckedChangedCommand.Execute(this);  
  142.         }  
  143.     }  
  144. }  
5) How to Bind contact list to the UI?
 
5.1 Displaying ContactList 
 
Models :

In Models we are going to create two classes BaseModel, ContactDetails.

1) BaseModel.cs 

Here we are implementing INotifyPropertychanged. In the future this class will be useful for ContactListPageViewModel, SelectedContactsViewModel.

  1. using System.ComponentModel;  
  2. namespace GetcontactsDemo.Models {  
  3.     public class BaseModel: INotifyPropertyChanged {  
  4.         public event PropertyChangedEventHandler PropertyChanged;  
  5.         protected virtual void OnPropertyChanged(string propertyName) {  
  6.             if (PropertyChanged != null) {  
  7.                 PropertyChanged(thisnew PropertyChangedEventArgs(propertyName));  
  8.             }  
  9.         }  
  10.     }  
  11. }  

2) ContactDetails.cs

This class properties will be useful to get contact data.

  1. namespace GetContactsDemo.Models {  
  2.     public class ContactDetails: BaseModel {  
  3.         public string FirstName {  
  4.             get;  
  5.             set;  
  6.         }  
  7.         public string LastName {  
  8.             get;  
  9.             set;  
  10.         }  
  11.         public string DisplayName {  
  12.             get;  
  13.             set;  
  14.         }  
  15.         public string EmailId {  
  16.             get;  
  17.             set;  
  18.         }  
  19.         public string Picture {  
  20.             get;  
  21.             set;  
  22.         }  
  23.         public string Number {  
  24.             get;  
  25.             set;  
  26.         }  
  27.         bool _isVisible;  
  28.         public bool IsVisible {  
  29.             get {  
  30.                 return _isVisible;  
  31.             }  
  32.             set {  
  33.                 _isVisible = value;  
  34.                 OnPropertyChanged("IsVisible");  
  35.             }  
  36.         }  
  37.         bool _isSelected;  
  38.         public bool IsSelected {  
  39.             get {  
  40.                 return _isSelected;  
  41.             }  
  42.             set {  
  43.                 _isSelected = value;  
  44.                 OnPropertyChanged("IsSelected");  
  45.             }  
  46.         }  
  47.     }  
  48. }  

Note:

IsVisible, IsSelected properties for CheckBox purpose.

Views:

Create your own XAML page named ContactListPage.xaml inside the Views folder and make sure to refer to "CheckBox" class in XAML by declaring a namespace for its location and using the namespace prefix on the control element.

ContactsListPage.xaml

  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="GetContactsDemo.Views.ContactsListPage" 
  5. BackgroundColor="#533F95" 
  6. xmlns:ctrls="clr-namespace:GetContactsDemo.CustomControls" 
  7. Title="Contacts">  
  8.     <ContentPage.ToolbarItems>  
  9.         <ToolbarItem Text="Select" Priority="0" Order="Primary" Command="{Binding SelectContactCommand}" /> </ContentPage.ToolbarItems>  
  10.     <StackLayout x:Name="stackPanel" VerticalOptions="FillAndExpand" Spacing="0">  
  11.         <SearchBar TextColor="#533F95" Text="{Binding SearchString}" CancelButtonColor="#533F95" Placeholder="Search" PlaceholderColor="#533F95" BackgroundColor="White" />  
  12.         <ListView x:Name="listView" BackgroundColor="#533F95" SeparatorColor="Silver" HasUnevenRows="true" SelectedItem="{Binding SelectedContact, Mode=TwoWay}" ItemsSource="{Binding SearchContactList}">  
  13.             <ListView.ItemTemplate>  
  14.                 <DataTemplate>  
  15.                     <ViewCell>  
  16.                         <StackLayout Padding="20" Orientation="Horizontal">  
  17.                             <Label Text="{Binding DisplayName}" VerticalTextAlignment="Center" TextColor="White" FontSize="20" />  
  18.                             <ctrls:CheckBox x:Name="cbUS" IsVisible="{Binding IsVisible}" IsChecked="{Binding IsSelected}" BorderImageSource="check_box_border.png" CheckedBackgroundImageSource="checked_bg.png" CheckmarkImageSource="check_mark.png" HorizontalOptions="EndAndExpand" /> </StackLayout>  
  19.                     </ViewCell>  
  20.                 </DataTemplate>  
  21.             </ListView.ItemTemplate>  
  22.         </ListView>  
  23.         <StackLayout Padding="20">  
  24.             <Button Text="Go" HorizontalOptions="FillAndExpand" Command="{Binding NavigationCommand}" BackgroundColor="White" TextColor="#533F95" /> </StackLayout>  
  25.     </StackLayout>  
  26. </ContentPage>  

The "ctrls" namespace prefix can be named anything. However, the clr-namespace and assembly values must match the details of the CheckBox class. Once the namespace is declared the prefix is used to reference the custom control.

ContactsListPage.xaml.cs

Make BindingContext in code behind with ContactListPageViewModel.

  1. using GetContactsDemo.Models;  
  2. using GetContactsDemo.ViewModels;  
  3. using Xamarin.Forms;  
  4. namespace GetContactsDemo.Views {  
  5.     public partial class ContactsListPage: ContentPage {  
  6.         public ContactsListPage() {  
  7.             InitializeComponent(); 
  8.             BindingContext = new ContactsListViewModel(Navigation);  
  9.             listView.ItemSelected += (sender, e) => {  
  10.                 var itemSelected = e.SelectedItem as ContactDetails;  
  11.                 if (itemSelected == null) {  
  12.                     return;  
  13.                 }  
  14.                 ((ListView) sender).SelectedItem = null;  
  15.             };  
  16.         }  
  17.     }  
  18. }  

View Models:

ContactsListPageViewModel.cs 

This ViewModel is used to display the ContactsList.

Properties

  • ContactList
  • SearchContactList
  • SearchString

Commands

  • SelectedContactCommand 
  • NavigationCommand
  1.  
  2. using System.Collections.Generic;  
  3. using System.Collections.ObjectModel;  
  4. using System.Linq;  
  5. using System.Windows.Input;  
  6. using GetContactsDemo.DependencyServices;  
  7. using GetContactsDemo.Models;  
  8. using Xamarin.Forms;  
  9. namespace GetContactsDemo.ViewModels {  
  10.     public class ContactsListViewModel: BaseModel {  
  11.         public ICommand SelectContactCommand {  
  12.             get;  
  13.             private set;  
  14.         }  
  15.         public ICommand NavigationCommand {  
  16.             get;  
  17.             private set;  
  18.         }  
  19.         public INavigation _navigation;  
  20.         ObservableCollection<ContactDetails> _contactList;  
  21.         public ObservableCollection<ContactDetails> ContactList {  
  22.             get {  
  23.                 return _contactList;  
  24.             }  
  25.             set {  
  26.                 _contactList = value;  
  27.                 OnPropertyChanged("ContactList");  
  28.             }  
  29.         }  
  30.         IEnumerable<ContactDetails> _searchContactList;  
  31.         public IEnumerable<ContactDetails> SearchContactList {  
  32.             get {  
  33.                 return _searchContactList;  
  34.             }  
  35.             set {  
  36.                 _searchContactList = value;  
  37.                 OnPropertyChanged("SearchContactList");  
  38.             }  
  39.         }  
  40.         string _searchString;  
  41.         public string SearchString {  
  42.             get {  
  43.                 return _searchString;  
  44.             }  
  45.             set {  
  46.                 _searchString = value;  
  47.                 SearchContactList = string.IsNullOrEmpty(value) ? ContactList : Where(i => i.DisplayName.ToLower().Contains(value.ToLower()));  
  48.                 OnPropertyChanged("SearchString");  
  49.             }  
  50.         }  
  51.         public ContactsListViewModel(INavigation navigation) {  
  52.             _navigation = navigation;  
  53.             GetAllContacts();  
  54.             SelectContactCommand = new Command(() => SelectContact());  
  55.             NavigationCommand = new Command(() => Navigation_Page());  
  56.         }  
  57.         public async void GetAllContacts() {  
  58.             var _contactService = DependencyService.Get<IContactService>();  
  59.             var contacts = await _contactService.GetAllContacts();  
  60.             ContactList = new ObservableCollection<ContactDetails>(contacts);  
  61.             SearchContactList = ContactList;  
  62.         }  
  63.         void SelectContact() {  
  64.             foreach(var checkbox in ContactList) {  
  65.                 checkbox.IsVisible = true;  
  66.             }  
  67.         }  
  68.         void Navigation_Page() { 
  69.            if(ContactList.Count>0){ 
  70.             var selectedContactsList = ContactList.Where(x => x.IsSelected == true).ToList();  
  71.             if (selectedContactsList.Count > 0) {  
  72.                 _navigation.PushAsync(new Views.SelectedContactsPage(selectedContactsList));  
  73.             } else {  
  74.                 App.Current.MainPage.DisplayAlert("GetContactsDemo""Please select atleast one contact",
  75. "Ok");  
  76.             } else {
  77.                 App.Current.MainPage.DisplayAlert("GetContactsDemo", "There is no contacts on your phone!", "Ok");
  78.            } 
  79.         }  
  80.     }  
  81. }  

5.2 Displaying  Selected ContactaList

Views:

Create your own XAML page named SelectContctsPage.xaml inside the Views folder. And  this will display selected contacts from ContactListPage.

SelectedContactsPage.xaml

  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="GetContactsDemo.Views.SelectedContactsPage" 
  5. Title="Selected Contacts">  
  6.     <StackLayout x:Name="stackPanel" VerticalOptions="FillAndExpand" Spacing="0">  
  7.         <ListView x:Name="listView" BackgroundColor="#533F95" SeparatorColor="Silver" HasUnevenRows="true" 
  8.            ItemsSource="{Binding SelectedContactList}">  
  9.             <ListView.ItemTemplate>  
  10.                 <DataTemplate>  
  11.                     <ViewCell>  
  12.                         <StackLayout Padding="10">  
  13.                             <Label Text="{Binding DisplayName}" VerticalTextAlignment="Center" TextColor="White" FontSize="20" />  
  14.                             <Label Text="{Binding Number}" VerticalTextAlignment="Center" TextColor="White" FontSize="20" /> </StackLayout>  
  15.                     </ViewCell>  
  16.                 </DataTemplate>  
  17.             </ListView.ItemTemplate>  
  18.         </ListView>  
  19.     </StackLayout>  
  20. </ContentPage>  

SelectedContactsPage.xaml.cs

Make BindingContext in code behind with SelectedContactsViewModel

  1. using System.Collections.Generic;  
  2. using GetContactsDemo.Models;  
  3. using GetContactsDemo.ViewModels;  
  4. using Xamarin.Forms;  
  5. namespace GetContactsDemo.Views {  
  6.     public partial class SelectedContactsPage: ContentPage {  
  7.         public SelectedContactsPage(List<ContactDetails> SelectedList) {  
  8.             InitializeComponent();  
  9.             BindingContext = new SelectedContactsViewModel(SelectedList);  
  10.         }  
  11.     }  
  12. }  

ViewModel:

SelectedContactsPageViewModel.cs

This viewmodel is used to display the selected contacts list.

Properties

  • SelectedContactList 
  1. using System.Collections.Generic;  
  2. using System.Collections.ObjectModel;  
  3. using GetContactsDemo.Models;  
  4. namespace GetContactsDemo.ViewModels {  
  5.     public class SelectedContactsViewModel: BaseModel {  
  6.         private ObservableCollection<ContactDetails> _selectedContactList;  
  7.         public ObservableCollection<ContactDetails> SelectedContactList {  
  8.             get {  
  9.                 return _selectedContactList;  
  10.             }  
  11.             set {  
  12.                 _selectedContactList = value;  
  13.                 OnPropertyChanged("SelectedContactList");  
  14.             }  
  15.         }  
  16.         public SelectedContactsViewModel(List<ContactDetails> SelectedList) {  
  17.             SelectedContactList = new ObservableCollection<ContactDetails>(SelectedList);  
  18.         }  
  19.     }  
  20. }  
6) How to change the NavigationBar Background and TextColor?

In App.cs we are changing NavigationBar Background and TextColor.

App.xaml.cs

  1. using Xamarin.Forms;  
  2. namespace GetContactsDemo {  
  3.     public partial class App: Application {  
  4.         public App() {  
  5.             InitializeComponent();  
  6.             MainPage = new NavigationPage(new Views.ContactsListPage()) {  
  7.                 BarBackgroundColor = Color.From#99312d,   
  8.                 BarTextColor= Color.White  
  9.             };  
  10.         }  
  11.         protected override void OnStart() {  
  12.             // Handle when your app start   
  13.         }  
  14.         protected override void OnSleep() {  
  15.             // Handle when your app sleeps   
  16.         }  
  17.         protected override void OnResume() {  
  18.             // Handle when your app resumes   
  19.         }  
  20.     }  
  21. }  

Output:

Please, download sample from here.
 
         


Similar Articles