简体   繁体   中英

Selecting contacts in windows phone 8

I am trying to add a basic contact list into my app.

So far, the app queries the contact store and displays all in a list.

What I require is a data structure containing the name and number of each contact that the user has selected from the list.

I would love to see your ideas. I am sure it will be something simple I have missed, but I have tried so much I am now very much confused.

Here is the relevant code snippet and accompanying XAML. Thank you so much for your time. C# UPDATED

namespace appNamespace
{
    public partial class contact : PhoneApplicationPage
    {
        public class CustomContact
        {
            public string Name { get; set; }
            public string Number { get; set; }

            public CustomContact()
            {
            }

            //CTOR that takes in a Contact object and extract the two fields we need (can add more fields)
            public CustomContact(Contact contact)
            {
                Name = contact.DisplayName;
                var number = contact.PhoneNumbers.FirstOrDefault();
                if (number != null)
                    Number = number.PhoneNumber;
                else
                    Number = "";
            }
        }

        public contact()
        {
            InitializeComponent();
        }

        private void showContacts(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());
            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";
            }
        }

        public void saveContacts(object sender, RoutedEventArgs e)
        {
            List<CustomContact> listOfContacts = new List<CustomContact>();

            listOfContacts = e.Results.Select(x => new CustomContact()
            {
                Number = x.PhoneNumbers.FirstOrDefault() != null ? x.PhoneNumbers.FirstOrDefault().PhoneNumber : "",
                Name = x.DisplayName
            }).ToList();
        }

        private void ContactResultsData_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Contact contact = ContactResultsData.SelectedItem as Contact;
            if (contact != null)
            {
                CustomContact customContact = new CustomContact(contact);
            }
        }

    }
}

XAML

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <StackPanel Height="Auto" Width="Auto" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="0,0,0,10" >

                <TextBlock Name="ContactResultsLabel" Text="results are loading..." Style="{StaticResource PhoneTextLargeStyle}" TextWrapping="Wrap" />

                <ListBox Name="ContactResultsData" ItemsSource="{Binding}" Height="436" Margin="12,0" SelectionMode="Multiple" >
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <TextBlock Name="ContactResults" FontSize="{StaticResource PhoneFontSizeMedium}" Text="{Binding Path=DisplayName, Mode=OneWay}" />
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
            </StackPanel>
            <Button x:Name="showButton" Content="Show Contacts" HorizontalAlignment="Left" VerticalAlignment="Top" Width="218" Height="90" Margin="0,531,0,0" Click="showContacts"/>
            <Button x:Name="saveButton" Content="Save Contacts" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="238,531,0,0" Width="218" Height="90" Click="saveContacts"/>
        </Grid>

You can create your class

public class CustomContact
{
   public string Name { get; set; }
   public string Number { get; set; }

   public CustomContact()
    {
    }

    //CTOR that takes in a Contact object and extract the two fields we need (can add more fields)
    public CustomContact(Contact contact)
    {
        DisplayName = contact.DisplayName;
        var number = contact.PhoneNumbers.FirstOrDefault();
        if(number != null)
            Number = number.PhoneNumber;
        else
            Number = "";
    }
}

And then iterate through the results and add them to your class

List<CustomContact> listOfContacts = new List<CustomContact>();
foreach (var c in e.Results)
{
    CustomContact contact  = new CustomContact();
    contact.DisplayName = c.DisplayName;
    var number = c.PhoneNumbers.FirstOrDefault(); //change this to whatever number you want
    if (number != null)
        contact.Number = number.PhoneNumber;
    else
        contact.Number = "";

    listOfContacts.Add(contact);
}
ContactResultsData.DataContext = listOfContacts;

You could shorten the foreach loop above into a single LINQ query

listOfContacts = e.Results.Select(x => new CustomContact() 
                                  { 
                                     Number = x.PhoneNumbers.FirstOrDefault() != null ? x.PhoneNumbers.FirstOrDefault().PhoneNumber : "", 
                                     DisplayName = x.DisplayName 
                                  }).ToList();

Update based on comment.

Assuming you don't use the above method, the ListBox will be filled with Contact objects (and not our CustomContact objects). We therefore convert the selected item into a Contact object and use the overloaded constructor that takes in a Contact object to create the CustomContact object that we want.

private void ContactResultsData_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    Contact contact = ContactResultsData.SelectedItem as Contact;
    if (contact != null)
    {
        CustomContact customContact = new CustomContact(contact);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM