Click here to Skip to main content
15,867,488 members
Articles / Mobile Apps / Windows Phone 7

How to Search for a Contact in WP7 using the Contacts Class?

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
4 Apr 2012CPOL3 min read 21.8K   1   1
How to programmatically search for a specific contact in WP7?

In last two blog posts, we learnt how to programmatically Save Contacts in WP7 and Retrieve Contact Information. Now after these, you may want to programmatically search for a specific contact. So how to do this?

Windows Phone 7 SDK provides that API for you. You can use that API to asynchronously search for a contact by different parameters. Continue reading the complete post to learn more about the class and search mechanism. Don’t forget to read my other blog posts too.

Know About the API

The phone 7 SDK provides a sealed class called “Contacts” derived from “PhoneDataSharingContext”. You can find this class in the namespace “Microsoft.Phone.UserData”, which provides an asynchronous method named “SearchAsynch()”. This method takes search query string and kinds of filter as parameter to search for the specific keywords. The “SearchCompleted” event returns the matched contacts to the user.

Here is the meta data of the “Contacts” class:

C#
namespace Microsoft.Phone.UserData
{
    public sealed class Contacts : PhoneDataSharingContext
    {
        public IEnumerable<Account> Accounts { get; }
        public void SearchAsync(string filter, FilterKind filterKind, object state);
        public event EventHandler<ContactsSearchEventArgs> SearchCompleted;
    }
}

The SDK also provides an enum named “FilterKind” which provides filter type for your search query. When set, this will allow you to search based on “PinnedToStart”, “EmailAddress”, “PhoneNumber” and “DisplayName”. This is also present in the “Microsoft.Phone.UserData” namespace.

Here is the meta data of the FilterKind enum:

C#
namespace Microsoft.Phone.UserData
{
    public enum FilterKind
    {
        None,
        PinnedToStart,
        EmailAddress,
        PhoneNumber,
        DisplayName,
    }
}

Hope you are now clear about the basic API. Let’s jump start with the implementation of the same.

Implementation Steps

Let us first start creating the UI for our demo with a Search TextBox and a ListBox where the result will be displayed. Now open the MainPage.xaml and modify the ContentPanel as below:

ASP.NET
<!--ContentPanel - place additional content here-->
<StackPanel x:Name="ContentPanel" 
Grid.Row="1" Margin="12,0,12,0">
    <TextBox x:Name="searchBox" 
    TextChanged="ContactsSearchBoxTextChanged"/>
    <ListBox x:Name="contactsList" Height="520">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Vertical">
                    <TextBlock Text="{Binding DisplayName}" 
                               Style="{StaticResource PhoneTextLargeStyle}"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</StackPanel>

Now, create the instance of the Contacts class and register for the “SearchCompleted” event. Now do an asynchronous search with empty string in the constructor. This will result out the complete list of contacts in the screen. Set “FilterKind” as DisplayName to search based on the same. Here is the sample code snippet:

C#
// Create instance of Contacts as member object
private readonly Contacts m_contacts = new Contacts();

// Register for "SearchCompleted" event and do Empty Search
m_contacts.SearchCompleted += ContactsSearch;
m_contacts.SearchAsync(string.Empty, FilterKind.DisplayName, null);

In the TextChanged event implementation, call the SearchAsync() method once again but this time pass the search text from the searchTextBox. This will fire the proper search based on the query term.

Let’s have a look into the below code:

C#
private void ContactsSearchBoxTextChanged(object sender, TextChangedEventArgs e)
{
    m_contacts.SearchAsync(searchBox.Text, FilterKind.DisplayName, null);
}

Now in the “SearchCompleted” event implementation, get the e.Results and set it to the ItemsSource of the ListBox. You can do anything here with the data. Make sure that, you bind data in the XAML page correctly.

C#
void ContactsSearch(object sender, ContactsSearchEventArgs e)
{
    try
    {
        // Set the Results to the ItemsSource
        contactsList.ItemsSource = e.Results;
    }
    catch
    {
    }
}

Here are the screenshots of what we implemented as of now. In the first screen, you can see all the contacts in the list. When you start typing in the Search TextBox, you will see the filtered Contacts in the list based on what you are typing.

image     image

Hope this post will be helpful for you to understand the API and the basics of contact search. Stay tuned to my blog, Twitter, or Facebook to read more articles, tutorials, news, tips & tricks on various technology fields.

Reference: http://www.kunal-chowdhury.com.

You may like to follow me on twitter @kunal2383 or may like the Facebook page of my blog http://www.facebook.com/blog.kunal2383.

This article was originally posted at http://www.kunal-chowdhury.com/feeds/posts/default

License

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


Written By
Technical Lead
India India

Kunal Chowdhury is a former Microsoft "Windows Platform Development" MVP (Most Valuable Professional, 2010 - 2018), a Codeproject Mentor, Speaker in various Microsoft events, Author, passionate Blogger and a Senior Technical Lead by profession.

He is currently working in an MNC located in India. He has a very good skill over XAML, C#, Silverlight, Windows Phone, WPF and Windows app development. He posts his findings, articles, tutorials in his technical blog (www.kunal-chowdhury.com) and CodeProject.


Books authored:


Connect with Kunal on:





Comments and Discussions

 
QuestionHow to Highlight the searchtext in the result? Pin
Gopinath P23-Dec-12 23:38
Gopinath P23-Dec-12 23:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.