Click here to Skip to main content
15,881,882 members
Articles / Web Development / ASP.NET
Tip/Trick

Selecting Phone Book Contacts in Windows Phone using MVVM

Rate me:
Please Sign up or sign in to vote.
4.67/5 (2 votes)
31 Jan 2014CPOL1 min read 11.2K   186   3  
The article describes how to select all the contacts in Windows Phone 7 and 8

Introduction

The tip describes how to select all the contacts and respective data in Windows Phone 7 and 8.

Background

Windows phone API allows us to access the phone book contact list using the code. Contacts are fetched in an observable list with details like Display Name, Company, Phone Number, etc. bundled in the Contacts object. These contacts can then be displayed in a list box with the required details.
Following examples demonstrate the same.

Using the Code

We will use the Contacts class to fetch the details of phone book contacts.
To start with Windows Phone Contacts class, the first and foremost requirement is that of adding a capability of ID_CAP_CONTACTS in the WMAppManifest.xml file.
To add a capability, either edit the XML or select the Capabilities tab from WMAppManifest.xml file and select the ID_CAP_CONTACTS check box located in the left part of the screen.

XML representation of the capability in WMAppManifest.xml:

XML
<Capabilities>
 <Capability Name="ID_CAP_CONTACTS" />
</Capabilities>  

Pictorial representation of the capabilities in WMAppManifest.xml:

Image 1

Now it’s time to move with the code to fetch the contact details. Let’s display all contacts using the search method from the Contacts class in MVVM pattern.

MainPage.xaml

C#
<Grid x:Name="LayoutRoot" Background="Transparent">
        <ListBox x:Name="lbMyContactNames" ItemsSource="{Binding Path=ListContactData}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Path=ContactName}" Margin="20" />
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
</Grid> 

MainPage.xaml.cs

C#
// Constructor
public MainPage()
{
     InitializeComponent();
 
     //assign the data context object
     lbMyContactNames.DataContext = new ContactsDemoViewModel();
} 

ContactsDemoViewModel.cs

C#
using Microsoft.Phone.UserData;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
 
namespace ContactsChooser
{
    class ContactsDemoViewModel : INotifyPropertyChanged
    { 
        //property changed event
        public event PropertyChangedEventHandler PropertyChanged;
        private Contacts myPersonalContacts;
        private List<string> listData;
 
        /// <summary>
        /// property to set the list of names
        /// takes object of the type ContactsDemoModel
        /// </summary>
        public List<ContactsDemoModel> ListContactData{get;set;}
 
        /// <summary>
        /// Constructor define the search criteria here
        /// so as to load the data on app start
        /// </summary>
        public ContactsDemoViewModel() {
 
            //Create an object of the search class
            myPersonalContacts = new Contacts();
 
            //perform search with a Blank parameter to get all details
            myPersonalContacts.SearchCompleted += myPersonalContacts_SearchCompleted;
 
            //create the list object
            listData = new List<string>();
 
            //test object my name passed so as to check the object being retrieved in state
            string myName = "Anobik Dey";
 
            //start the search and wait for it to complete - async method
            myPersonalContacts.SearchAsync(string.Empty, FilterKind.DisplayName, myName);
        }
 
        /// <summary>
        /// Event fired when search is complete
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void myPersonalContacts_SearchCompleted(object sender, ContactsSearchEventArgs e)
        {
            ListContactData = new List<ContactsDemoModel>();
 
            //results will be populated in the ContactsSearchEventArgs object
            //so loop through and add to the list
            for (int i = 0; i < e.Results.Count(); i++) {
 
                //add contact data to new ContactsDemoModel object so as to bind to text box
                ListContactData.Add(new ContactsDemoModel()
                {ContactName = e.Results.ElementAt(i).DisplayName});
                 
            }
            //raise the property changed event to reflect data in the list
             RaisePropertyChanged("ListContactData");
        }
 
        /// <summary>
        /// Event raised when we add a value to a property
        /// </summary>
        /// <param name="property"></param>
        protected void RaisePropertyChanged(string property)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(property));
            }
        }
    }
} 

ContactsDemoModel.cs

C#
class ContactsDemoModel
    {
        public string ContactName{get;set;}
    } 

Points of Interest

Using the above code, we can display the names of all contacts in the list box. For selecting a particular set of contacts, we can use the SearchAsync function with the search parameters while for fetching all the contacts. we can search with a string.Empty or a blank ("") argument as a result of which all the contacts will be fetched.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Mindfire Solutions
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --