How to access contact data for Windows Phone 8

July 21, 2014

Applies to: Windows Phone 8 and Windows Phone Silverlight 8.1 | Windows Phone OS 7.1

The process for accessing contact data is to get a reference to the Contacts object, perform an asynchronous search on it, and then capture the results as a collection of Contact objects. You can use the results in different ways, and this topic demonstrates how to bind the results to the user interface or to enumerate through the results.

This topic discusses read-only access to user’s contact data. For information on creating a custom contact store for your app that provides read and write access, see Custom contact store for Windows Phone 8.

This topic contains the following sections.

In this procedure, you put the code in a button click event for testing purposes only. In your own applications, you can access contact data wherever you need it. The following procedure assumes that you have a Windows Phone application that has a page with a button named ButtonContacts. In this procedure, you set the filter kind to None, which returns all contacts. For more information, see Contact filtering and matching for Windows Phone 8.

NoteNote:

Windows Phone Emulator contains sample contacts. You can test these procedures using Windows Phone Emulator or a physical device.

To access contact data

  1. At the top of the code-behind file for your page, add the following statement.

    using Microsoft.Phone.UserData;
    
  2. Add the following code. It contains the button click event and the method to handle the completed event of the asynchronous search.

    private void ButtonContacts_Click(object sender, RoutedEventArgs e)
    {
        Contacts cons = new Contacts();
    
        //Identify the method that runs after the asynchronous search completes.
        cons.SearchCompleted += new EventHandler<ContactsSearchEventArgs>(Contacts_SearchCompleted);
    
        //Start the asynchronous search.
        cons.SearchAsync(String.Empty, FilterKind.None, "Contacts Test #1");
    }
    
    void Contacts_SearchCompleted(object sender, ContactsSearchEventArgs e)
    {
        //Do something with the results.
        MessageBox.Show(e.Results.Count().ToString());
    }
    

In this procedure, you data-bind the results of a contact search directly to the user interface. This procedure assumes you have completed the procedure “Accessing Contact Data” in the preceding section.

To data-bind contact data

  1. Open the XAML editor for your page and add the following code. You can add the code to the Content Panel or Layout Root GRID element. This XAML creates a list box that you bind to the contact data. The data template for each row of the list box contains the name of the contact. In your applications, you can create any data templates that you like. For more information, see Data binding for Windows Phone 8 and Data Templating Overview.

    <StackPanel Height="Auto" Width="Auto" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" >
    
        <TextBlock Name="ContactResultsLabel" Text="results are loading..." Style="{StaticResource PhoneTextLargeStyle}" TextWrapping="Wrap" />
    
        <ListBox Name="ContactResultsData" ItemsSource="{Binding}" Height="200" Margin="24,0,0,0" >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Name="ContactResults" Text="{Binding Path=DisplayName, Mode=OneWay}" />
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </StackPanel>
    
  2. In the code-behind for your page, replace the existing event handler with the following code. This code binds the contact data to the user interface by setting the data context of the list box equal to the results of the search. It includes error handling in case there are no results. The code also changes the text of the list box label depending on whether there are results or not.

    void Contacts_SearchCompleted(object sender, ContactsSearchEventArgs e)
    {
        try
        {
            //Bind the results to the user interface.
            ContactResultsData.DataContext = e.Results;
        }
        catch (System.Exception)
        {
            //No results
        }
    
        if (ContactResultsData.Items.Any())
        {
            ContactResultsLabel.Text = "results";
        }
        else
        {
            ContactResultsLabel.Text = "no results";
        }
    }
    
  3. Save and build your solution.

  4. Start your application and click the button.

    The data appears in the list box.

In this procedure, you enumerate the results of a contact search and display the results in a message box. This procedure assumes you have completed the procedure “Accessing Contact Data” in a preceding section of this topic.

To enumerate contact data

  1. In the code-behind for your page, replace the existing event handler with the following code. This code enumerates the contact data by using a for-each loop.

    void Contacts_SearchCompleted(object sender, ContactsSearchEventArgs e)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
    
        foreach (Contact con in e.Results)
        {
            sb.AppendLine(con.DisplayName);
        }
    
        MessageBox.Show(sb.ToString());
    }
    
  2. Save and build your solution.

  3. Start your application and click the button.

    The message box appears.

In this procedure, you use LINQ to refine the results of a contact search. You data-bind the results directly to the user interface. This procedure assumes you have completed the procedure “Accessing Contact Data” in a preceding section of this topic.

Caution noteCaution:

Contact data can vary widely in size. LINQ is slower than using the built-in searches, which are pre-indexed. If possible, you should use the built-in search filters. For more information, see Contact filtering and matching for Windows Phone 8.

To use LINQ

  1. In the code-behind for your page, replace the existing event handler with the following code. This code queries the results for contacts that have email addresses that contain “example.” Two of the sample contacts in Windows Phone Emulator contain this string.

    void Contacts_SearchCompleted(object sender, ContactsSearchEventArgs e)
    {
        try
        {
            ContactResultsDataLINQ.DataContext =
                from Contact con in e.Results
                from ContactEmailAddress a in con.EmailAddresses
                where a.EmailAddress.Contains("example")
                select con;
        }
        catch (System.Exception)
        {
            //No results
        }
    }
    
  2. Open the XAML editor for your page and add the following code. You can add the code to the Content Panel or Layout Root GRID element. This XAML creates a list box that you bind to the contact data. Each row of the list box contains the email address of the contact. Note that each contact can have more than one email address; this XAML displays the first one.

    <ListBox Name="ContactResultsDataLINQ" ItemsSource="{Binding}" Height="200" Margin="24,0,0,0" >
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock Text="{Binding Path=EmailAddresses[0].EmailAddress, Mode=OneWay}" />
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
    
  3. Save and build your solution.

  4. Start your application and click the button.

    The filtered data appears in the list box. If you are testing on Windows Phone Emulator, you will see the following.

    Chris@example.com

    Julia@example.com

Show:
© 2014 Microsoft