Condividi tramite


How to access contact data for Windows Phone 8

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

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.

Accessing Contact Data

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.

Note

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;
    
    Imports 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());
    }
    
    Private Sub ButtonContacts_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
    
        Dim cons As Contacts = New Contacts()
    
        'Identify the method that runs after the asynchronous search completes.
        AddHandler cons.SearchCompleted, AddressOf Contacts_SearchCompleted
    
        'Start the asynchronous search.
        cons.SearchAsync(String.Empty, FilterKind.None, "Contacts Test #1")
    End Sub
    
    Private Sub Contacts_SearchCompleted(sender As Object, e As ContactsSearchEventArgs)
    
        'Do something with the results.
        MessageBox.Show(e.Results.Count().ToString())
    End Sub
    

Data-Binding Contact Data Results

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";
        }
    }
    
    Private Sub Contacts_SearchCompleted(sender As Object, e As ContactsSearchEventArgs)
    
        Try
            'Bind the results to the user interface.
            ContactResultsData.DataContext = e.Results
    
        Catch ex As System.Exception
    
            'No results
        End Try
    
        If ContactResultsData.Items.Any() Then
    
            ContactResultsLabel.Text = "results"
        Else
            ContactResultsLabel.Text = "no results"
        End If
    End Sub
    
  3. Save and build your solution.

  4. Start your application and click the button.

    The data appears in the list box.

Enumerating Contact Data Results

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());
    }
    
    Private Sub Contacts_SearchCompleted(sender As Object, e As ContactsSearchEventArgs)
    
        Dim sb As System.Text.StringBuilder = new System.Text.StringBuilder()
    
        For Each con As Contact In e.Results
    
            sb.AppendLine(con.DisplayName)
        Next
    
        MessageBox.Show(sb.ToString())
    End Sub
    
  2. Save and build your solution.

  3. Start your application and click the button.

    The message box appears.

LINQ

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.

Warning

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
        }
    }
    
    Private Sub Contacts_SearchCompleted(sender As Object, e As ContactsSearchEventArgs)
    
        Try
            'Bind the results to the user interface.
            ContactResultsDataLINQ.DataContext = _
                From con As Contact In e.Results _
                From a As ContactEmailAddress In con.EmailAddresses _
                Where a.EmailAddress.Contains("example") _
                Select con
    
        Catch ex As System.Exception
    
            'No results
        End Try
    End Sub
    
  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

See Also

Reference

Microsoft.Phone.UserData

Contacts..::.SearchAsync

Contacts..::.SearchCompleted

Other Resources

Walkthrough: Accessing contact and calendar data for Windows Phone 8

How to access calendar data for Windows Phone 8

Code Samples for Windows Phone