Share via


Quickstart: Selecting user contacts (XAML)

[This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation]

Through the Windows.ApplicationModel.Contacts namespace, you have several options for selecting contacts. Here, we'll show you how to select a single contact or multiple contacts, and we'll show you how to configure the contact picker to retrieve only the contact information that your app needs.

Prerequisites

  • We recommend that you be familiar with Microsoft Visual Studio and its associated templates.
  • We recommend that you be familiar with C# development.

Set up the contact picker

Create an instance of Windows.ApplicationModel.Contacts.ContactPicker and assign it to a variable.

var contactPicker = new Windows.ApplicationModel.Contacts.ContactPicker();

Provide a name for the commit button

The commit button is the button that the user presses to confirm the contact that they selected. Set the name of this button with Windows.ApplicationModel.Contacts.CommitButtonText.

contactPicker.CommitButtonText = "Select";

Note  For Windows Phone Store apps, the CommitButtonText property is unsupported.

Set the selection mode (optional)

By default, the contact picker retrieves all of the available data for the contacts that the user selects. The SelectionMode property lets you configure the contact picker to retrieve only the data fields that your app needs. This is a more efficient way to use the contact picker if you only need a subset of the available contact data.

First, set the SelectionMode property to Fields:

contactPicker.SelectionMode = Windows.ApplicationModel.Contacts.ContactSelectionMode.Fields;

Note  For Windows Phone Store apps, the SelectionMode property is unsupported.

Then, use the desiredFieldsWithContactFieldType property to specify the fields that you want the contact picker to retrieve. This example configures the contact picker to retrieve email addresses:

contactPicker.desiredFieldsWithContactFieldType.append(Windows.ApplicationModel.Contacts.ContactFieldType.email);

Launch the picker

Now you can launch the picker. Use pickContactAsync if you want the user to select only one contact.

Contact contact = await contactPicker.PickContactAsync();

Use pickContactsAsync if you want the user to select one or more contacts.

public IList<Contact> contacts;
contacts = await contactPicker.PickContactsAsync();

Process the contacts

When the picker returns, check whether the user has selected any contacts. If so, process the contact information.

This example shows how to processes a single contact. Here we retrieve the contact's name and copy it into a TextBlock control. We also retrieve the contact's thumbnail image and copy it into an Image control.

if (contact != null)
{
    OutputName.Text = contact.FirstName;

    IRandomAccessStreamWithContentType stream = await contact.Thumbnail.OpenReadAsync();
    if (stream != null && stream.Size > 0)
    {
        BitmapImage bitmap = new BitmapImage();
        bitmap.SetSource(stream);
        OutputThumbnail.Source = bitmap;
    }

This example shows how to process multiple contacts.

if (contacts.Count > 0)
{
    foreach (Contact contact in contacts)
    {
        // Do something with the contact information.
    }
}

Complete example (single contact)

This example uses the contact picker to retrieve a single contact's name, email addresses, locations, and thumbnail image.

        private async void PickAContactButton_Click(object sender, RoutedEventArgs e)
        {
            var contactPicker = new Windows.ApplicationModel.Contacts.ContactPicker();
            contactPicker.CommitButtonText = "Select";
            Contact contact = await contactPicker.PickContactAsync();

            if (contact != null)
            {
                OutputFields.Visibility = Visibility.Visible;
                OutputEmpty.Visibility = Visibility.Collapsed;

                OutputName.Text = contact.DisplayName;
                AppendContactFieldValues(OutputEmailHeader, OutputEmails, contact.Emails);
                AppendContactFieldValues(OutputPhoneNumberHeader, OutputPhoneNumbers, contact.Phones);
                AppendContactFieldValues(OutputAddressHeader, OutputAddresses, contact.Addresses);

                if( contact.Thumbnail != null)
                {
                    IRandomAccessStreamWithContentType stream = await contact.Thumbnail.OpenReadAsync();
                    if (stream != null && stream.Size > 0)
                    {
                        BitmapImage bitmap = new BitmapImage();
                        bitmap.SetSource(stream);
                        OutputThumbnail.Source = bitmap;
                    }
                    else
                    {
                        OutputThumbnail.Source = null;
                    }
                }
            }
            else
            {
                OutputEmpty.Visibility = Visibility.Visible;
                OutputFields.Visibility = Visibility.Collapsed;
                OutputThumbnail.Source = null;
            }
            
        }

        private void AppendContactFieldValues<T>(TextBlock header, TextBlock content, IList<T> fields)
        {
            if (fields.Count > 0)
            {
                StringBuilder output = new StringBuilder();
                if(fields[0].GetType() == typeof(ContactEmail))
                {
                    foreach (ContactEmail email in fields as IList<ContactEmail>)
                    {
                        output.AppendFormat("Email Address: {0} ({1})\n", email.Address, email.Kind);
                    }
                }
                else if (fields[0].GetType() == typeof(ContactPhone))
                {
                    foreach (ContactPhone phone in fields as IList<ContactPhone>)
                    {
                        output.AppendFormat("Phone: {0} ({1})\n", phone.Number, phone.Kind);
                    }
                }
                else if(fields[0].GetType() == typeof(ContactAddress))
                {
                    List<String> addressParts = null;
                    string unstructuredAddress = "";

                    foreach (ContactAddress address in fields as IList<ContactAddress>)
                    {
                        addressParts = (new List<string> { address.StreetAddress, address.Locality, address.Region, address.PostalCode });
                        unstructuredAddress = string.Join(", ", addressParts.FindAll(s => !string.IsNullOrEmpty(s)));
                        output.AppendFormat("Address: {0} ({1})\n", unstructuredAddress, address.Kind);
                    }
                }
                
                header.Visibility = Visibility.Visible;
                content.Visibility = Visibility.Visible;
                content.Text = output.ToString();
            }
            else
            {
                header.Visibility = Visibility.Collapsed;
                content.Visibility = Visibility.Collapsed;
            }
        }

Complete example (multiple contacts)

This example uses the contact picker to retrieve multiple contacts and then adds the contacts to a ListView control called OutputContacts.

        MainPage rootPage = MainPage.Current;
        public IList<Contact> contacts;
        private async void PickContactsButton_Click(object sender, RoutedEventArgs e)
        {
            var contactPicker = new Windows.ApplicationModel.Contacts.ContactPicker();
            contactPicker.CommitButtonText = "Select";
            contacts = await contactPicker.PickContactsAsync();

            // Clear the ListView.
            OutputContacts.Items.Clear();

            if (contacts.Count > 0)
            {
                OutputContacts.Visibility = Windows.UI.Xaml.Visibility.Visible;
                OutputEmpty.Visibility = Visibility.Collapsed;

                foreach (Contact contact in contacts)
                {
                    // Add the contacts to the ListView.
                    OutputContacts.Items.Add(new ContactItemAdapter(contact));
                }
            }
            else
            {
                OutputEmpty.Visibility = Visibility.Visible;
            }         
        }
    public class ContactItemAdapter
    {
        public string Name { get; private set; }
        public string SecondaryText { get; private set; }
        public BitmapImage Thumbnail { get; private set; }

        public ContactItemAdapter(Contact contact)
        {
            Name = contact.DisplayName;
            if (contact.Emails.Count > 0)
            {
                SecondaryText = contact.Emails[0].Address;
            }
            else if (contact.Phones.Count > 0)
            {
                SecondaryText = contact.Phones[0].Number;
            }
            else if (contact.Addresses.Count > 0)
            {
                List<string> addressParts = (new List<string> { contact.Addresses[0].StreetAddress, 
                  contact.Addresses[0].Locality, contact.Addresses[0].Region, contact.Addresses[0].PostalCode });
                string unstructuredAddress = string.Join(", ", addressParts.FindAll(s => !string.IsNullOrEmpty(s)));
                SecondaryText = unstructuredAddress;
            }
            GetThumbnail(contact);
        }

        private async void GetThumbnail(Contact contact)
        {
            if (contact.Thumbnail != null)
            {
                IRandomAccessStreamWithContentType stream = await contact.Thumbnail.OpenReadAsync();
                if (stream != null && stream.Size > 0)
                {
                    Thumbnail = new BitmapImage();
                    Thumbnail.SetSource(stream);
                }
            }
        }
    }

Summary and next steps

Now you have a basic understanding of how to use the contact picker to retrieve contact information. Download the Contact Picker app sample from the code gallery to see more examples of how to use contacts and the contact picker.

Contact Picker app sample