Monday 21 May 2018

How to fetch Mobile contacts in Xamarin.Forms

Introduction:

In this article we can learn how to fetch mobile contacts using Xamarin.Mobile in Xamarin.Forms.

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 can explain you 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 to select contact from contact 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
    • Xamarin.Android
    • Xamarin.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.
    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.
    Then, we have to give the app name; i.e., GetContactsDemo.
    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.
    After clicking on the create button it will create the GetContactsDemo Xamarin.Forms project like below.
    And the project structure will be,
    • GetContactsDemo:  It is for Shared Code
    • GetContactsDemo.Droid:  It is for Android.
    • GetContactsDemo.iOS:  It is for iOS
    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.

    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.
    Step 3:
    In components folder we can check whether Xamarin.Mobile component added or not.
    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.     
    5. namespace GetContactsDemo.DependencyServices    
    6. {    
    7.     public interface IContactService    
    8.     {    
    9.         Task<IEnumerable<ContactDetails>> GetAllContacts();    
    10.     }    
    11. }    

    Xamarin.Android

    First we need to add permission 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">    
    6.     </application>    
    7. </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.   
    10. [assembly: Dependency(typeof(ContactService))]    
    11. namespace GetContactsDemo.Droid{    
    12.     public class ContactService : IContactService{    
    13.             
    14.         readonly Xamarin.Contacts.AddressBook _addressBook;    
    15.         static IEnumerable<ContactDetails> _contactsList;    
    16.     
    17.         public ContactService(){    
    18.             _addressBook = new Xamarin.Contacts.AddressBook(Forms.Context.ApplicationContext);    
    19.         }    
    20.     
    21.         public async Task<IEnumerable<ContactDetails>> GetAllContacts(){    
    22.             var contacts = new List<ContactDetails>();    
    23.             await _addressBook.RequestPermission().ContinueWith(t =>{    
    24.                 if (!t.Result){    
    25.                     App.Current.MainPage.DisplayAlert("GetContactsDemo""Sorry ! Permission was denied""Ok");    
    26.                     return;    
    27.                 }    
    28.                 foreach (var contact in _addressBook.ToList()){    
    29.                     contacts.Add(new ContactDetails(){    
    30.                         FirstName = contact.FirstName != null ? contact.FirstName : string.Empty,    
    31.                         LastName = contact.LastName != null ? contact.LastName : string.Empty,    
    32.                         DisplayName = contact.DisplayName != null ? contact.DisplayName : string.Empty,    
    33.                         EmailId = contact.Emails.FirstOrDefault() != null ? contact.Emails.FirstOrDefault().Address : String.Empty,    
    34.                         Number = contact.Phones.FirstOrDefault() != null ? contact.Phones.FirstOrDefault().Number : String.Empty,    
    35.                         IsVisible = false    
    36.                     });    
    37.                 }    
    38.             });    
    39.     
    40.             _contactsList = (from c in contacts orderby c.FirstName select c).ToList();    
    41.             return _contactsList;    
    42.         }    
    43.     }    
    44. }    

    Xamarin.iOS
    Giving permission in info.plist file for accessing contacts.
    info.plist:
    Key     :   Privacy - Contacts Usage Description     
    Value  :   Access Contacts(It's anything)

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

    4. How to create CheckBox to select contact from contact 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.


    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"      
    7.             x:Name="mainContainer"      
    8.             HorizontalOptions="FillAndExpand"      
    9.             VerticalOptions="FillAndExpand"      
    10.             Padding="0"      
    11.             Spacing="5">      
    12.             <AbsoluteLayout HorizontalOptions="Center"      
    13.                 VerticalOptions="Center"      
    14.                 WidthRequest="20"      
    15.                 HeightRequest="20"      
    16.                 x:Name="imageContainer">      
    17.                 <Image Source="{Binding CheckedBackgroundImageSource}"      
    18.                     x:Name="checkedBackground"      
    19.                     Aspect="AspectFit"      
    20.                     AbsoluteLayout.LayoutBounds="0.5, 0.5, 1, 1"      
    21.                     AbsoluteLayout.LayoutFlags="All"      
    22.                     Opacity="0"      
    23.                     InputTransparent="True"/>      
    24.                 <Image Source="{Binding BorderImageSource}"      
    25.                     x:Name="borderImage"      
    26.                     Aspect="AspectFit"      
    27.                     AbsoluteLayout.LayoutBounds="0.5, 0.5, 1, 1"      
    28.                     AbsoluteLayout.LayoutFlags="All"      
    29.                     InputTransparent="True"/>      
    30.                 <Image Source="{Binding CheckmarkImageSource}"      
    31.                     x:Name="checkedImage"      
    32.                     Aspect="AspectFit"      
    33.                     AbsoluteLayout.LayoutBounds="0.5, 0.5, 1, 1"      
    34.                     AbsoluteLayout.LayoutFlags="All"      
    35.                     Opacity="0"      
    36.                     InputTransparent="True"/>      
    37.             </AbsoluteLayout>      
    38.             <Label x:Name="controlLabel"      
    39.                 HorizontalOptions="FillAndExpand"      
    40.                 VerticalOptions="FillAndExpand"      
    41.                 HorizontalTextAlignment="Start"      
    42.                 VerticalTextAlignment="Center"      
    43.                 Text="{Binding Title}"      
    44.                 Style="{Binding LabelStyle}"      
    45.                 InputTransparent="True"/>      
    46.         </StackLayout>      
    47.     </ContentView.Content>      
    48. </ContentView>   
      

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

    5. How to Bind contact list to the UI?

    5.1. Displaying Contacts:
    Models:
    In Models we are going to create two classes BaseModel, ContactDetails.

    1) BaseModel.cs
    Here we are implementing INotifyPropertychanged, In future this class will useful for ContactListPageViewModel, SelectedContactsViewModel.

    1. using System.ComponentModel;    
    2.     
    3. namespace GetContactsDemo.Models    
    4. {    
    5.     public class BaseModel : INotifyPropertyChanged    
    6.     {    
    7.         public event PropertyChangedEventHandler PropertyChanged;    
    8.     
    9.         protected virtual void OnPropertyChanged(string propertyName)    
    10.         {    
    11.             if (PropertyChanged != null)    
    12.             {    
    13.                 PropertyChanged(this,    
    14.                     new PropertyChangedEventArgs(propertyName));    
    15.             }    
    16.         }    
    17.     }    
    18. }    

    2) ContactDetails.cs
    This class properties will useful to get contact data.

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

    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    
    10.             Text ="Select"    
    11.             Priority="0"    
    12.             Order="Primary"    
    13.             Command="{Binding SelectContactCommand}"/>    
    14.     </ContentPage.ToolbarItems>    
    15.     <StackLayout x:Name="stackPanel"    
    16.         VerticalOptions="FillAndExpand"    
    17.         Spacing="0">    
    18.         <SearchBar    
    19.             TextColor="#533F95"    
    20.             Text="{Binding SearchString}"    
    21.             CancelButtonColor="#533F95"    
    22.             Placeholder="Search"    
    23.             PlaceholderColor="#533F95"    
    24.             BackgroundColor="White"/>    
    25.         <ListView x:Name="listView"    
    26.             BackgroundColor="#533F95"    
    27.             SeparatorColor="Silver" HasUnevenRows="true"    
    28.             SelectedItem="{Binding SelectedContact, Mode=TwoWay}"    
    29.             ItemsSource="{Binding SearchContactList}">    
    30.             <ListView.ItemTemplate>    
    31.                 <DataTemplate>    
    32.                     <ViewCell>    
    33.                         <StackLayout Padding="20"    
    34.                             Orientation="Horizontal">    
    35.                             <Label Text="{Binding DisplayName}"    
    36.                                 VerticalTextAlignment="Center"    
    37.                                 TextColor="White" FontSize="20"/>    
    38.                             <ctrls:CheckBox x:Name="cbUS"    
    39.                                 IsVisible="{Binding IsVisible}"    
    40.                                 IsChecked="{Binding IsSelected}"    
    41.                                 BorderImageSource="check_box_border.png"    
    42.                                 CheckedBackgroundImageSource="checked_bg.png"    
    43.                                 CheckmarkImageSource="check_mark.png" HorizontalOptions="EndAndExpand"/>    
    44.                         </StackLayout>    
    45.                     </ViewCell>    
    46.                 </DataTemplate>    
    47.             </ListView.ItemTemplate>    
    48.         </ListView>    
    49.         <StackLayout Padding="20">    
    50.             <Button Text="Go" HorizontalOptions="FillAndExpand"    
    51.                 Command="{Binding NavigationCommand}"    
    52.                 BackgroundColor="White"    
    53.                 TextColor="#533F95"/>    
    54.         </StackLayout>    
    55.     </StackLayout>    
    56. </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 System.Linq;    
    2. using GetContactsDemo.CustomControls;    
    3. using GetContactsDemo.Models;    
    4. using GetContactsDemo.ViewModels;    
    5. using Xamarin.Forms;    
    6.     
    7. namespace GetContactsDemo.Views    
    8. {    
    9.     public partial class ContactsListPage : ContentPage    
    10.     {    
    11.         public ContactsListPage()    
    12.         {    
    13.             InitializeComponent();    
    14.             BindingContext = new ContactsListViewModel(Navigation);    
    15.     
    16.             listView.ItemSelected += (sender, e) =>    
    17.             {    
    18.                 var itemSelected = e.SelectedItem as ContactDetails;    
    19.                 if (itemSelected == null)    
    20.                 {    
    21.                     return;    
    22.                 }    
    23.                   ((ListView)sender).SelectedItem = null;    
    24.             };    
    25.         }    
    26.     }    
    27.   

    View Models:

    ContactsListPageViewModel.cs
    This ViewModel is used to display the ContactsList.
    Properties:
    • ContactList
    • SearchContactList
    • SearchString
    Commands:
    • SelectedContactCommand
    • NavigationCommand 

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

    5.2. Select Contacts: 

    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"     
    7.         VerticalOptions="FillAndExpand"     
    8.         Spacing="0">    
    9.         <ListView x:Name="listView"     
    10.             BackgroundColor="#533F95"     
    11.             SeparatorColor="Silver"     
    12.             HasUnevenRows="true"      
    13.             ItemsSource="{Binding SelectedContactList}">    
    14.             <ListView.ItemTemplate>    
    15.                 <DataTemplate>    
    16.                     <ViewCell>    
    17.                         <StackLayout Padding="10">    
    18.                         <Label Text="{Binding DisplayName}"     
    19.                             VerticalTextAlignment="Center"     
    20.                             TextColor="White"     
    21.                             FontSize="20"/>    
    22.                         <Label Text="{Binding Number}"     
    23.                             VerticalTextAlignment="Center"     
    24.                             TextColor="White"     
    25.                             FontSize="20"/>    
    26.                         </StackLayout>    
    27.                     </ViewCell>    
    28.                 </DataTemplate>    
    29.             </ListView.ItemTemplate>    
    30.         </ListView>    
    31.     </StackLayout>    
    32. </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.     
    6. namespace GetContactsDemo.Views    
    7. {    
    8.     public partial class SelectedContactsPage : ContentPage    
    9.     {    
    10.         public SelectedContactsPage(List<ContactDetails> SelectedList)    
    11.         {    
    12.             InitializeComponent();    
    13.             BindingContext = new SelectedContactsViewModel(SelectedList);    
    14.         }    
    15.     }    
    16. }    

    ViewModel:

    SelectedContactsPageViewModel.cs
    This viewmodel is used to display the selected contact list.
    Properties:
    • SelectedContactList
    1. using System.Collections.Generic;    
    2. using System.Collections.ObjectModel;    
    3. using GetContactsDemo.Models;    
    4.     
    5. namespace GetContactsDemo.ViewModels{    
    6.     public class SelectedContactsViewModel : BaseModel{    
    7.             
    8.         private ObservableCollection<ContactDetails> _selectedContactList;    
    9.         public ObservableCollection<ContactDetails> SelectedContactList{    
    10.             get {    
    11.                 return _selectedContactList;    
    12.             }    
    13.             set {    
    14.                 _selectedContactList = value;    
    15.                 OnPropertyChanged("SelectedContactList");    
    16.             }    
    17.         }    
    18.     
    19.         public SelectedContactsViewModel(List<ContactDetails> SelectedList) {    
    20.             SelectedContactList = new ObservableCollection<ContactDetails>(SelectedList);    
    21.         }    
    22.     }    
    23.   

    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.     
    3. namespace GetContactsDemo    
    4. {    
    5.     public partial class App : Application    
    6.     {    
    7.         public App()    
    8.         {    
    9.             InitializeComponent();    
    10.     
    11.             MainPage = new NavigationPage(new Views.ContactsListPage()){    
    12.                 BarBackgroundColor = Color.FromRgb(153,49,45),    
    13.                 BarTextColor=Color.White    
    14.             };    
    15.         }    
    16.     
    17.         protected override void OnStart()    
    18.         {    
    19.             // Handle when your app start    
    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. }   

    Output:


    Source Code:

    No comments:

    Post a Comment