question

VasanthakumarM-3635 avatar image
0 Votes"
VasanthakumarM-3635 asked JarvanZhang-MSFT commented

How to select the particular contact from contact list in the xamarin forms

Hi Techie,
How to select the particular contact from contact list in the Xamarin forms.

How to achieve it ?




dotnet-xamarin
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

How to select the particular contact from contact list in the Xamarin forms.

Try using Xamarin.Essentials.Contacts api to pick a contact and retrieve information about it. Don't forget to add the contacts permission when using the api.

private async void Button_Clicked(object sender, EventArgs e)
{
    try
    {
        var contact = await Contacts.PickContactAsync();

        if (contact == null)
            return;

        var displayName = contact.DisplayName;
        var phones = contact.Phones; // List of phone numbers
    }
    catch (Exception ex)
    {
        // Handle exception here.
    }
}

Check the doc: https://docs.microsoft.com/en-us/xamarin/essentials/contacts?tabs=android

0 Votes 0 ·

@JarvanZhang-MSFT this code is for pick an single contact from phone list and bind into the label or list view .

But my requirement : I need to select one or more contact from my phone contact list .later I need to bind into the list view .

How I will achieve this ?

0 Votes 0 ·
JarvanZhang-MSFT avatar image
0 Votes"
JarvanZhang-MSFT answered VasanthakumarM-3635 commented

I need to select one or more contact from my phone contact list .later I need to bind into the list view

To bind the selected data to a listView, try to set data binding for the listView as usual. Define an 'addItem' method in the ViewModel class, execute the method and pass the data after picking the contact.

Check the code:

//page.xaml
<StackLayout>
    <Button Text="click button" Clicked="Button_Clicked"/>
    <ListView x:Name="listview" ItemsSource="{Binding DataCollection}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <StackLayout>
                        <Label Text="{Binding Content}"/>
                    </StackLayout>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</StackLayout>

//page.xaml.cs
public partial class MainPage : ContentPage
{
    TestViewModel viewModel;
    public MainPage()
    {
        InitializeComponent();

        viewModel = new TestViewModel();
        BindingContext = viewModel;
    }

    private async void Button_Clicked(object sender, EventArgs e)
    {
        try
        {
            var contact = await Contacts.PickContactAsync();

            if (contact != null)
            {
                viewModel.AddItems(contact);
            }
        }
        catch (Exception ex)
        {
            // Handle exception here.
        }
    }
}

Model and ViewModel classes

public class TestModel : INotifyPropertyChanged
{
    private string content;
    public string Content
    {
        get
        {
            return content;
        }
        set
        {
            if (content != value)
            {
                content = value;
                NotifyPropertyChanged();
            }
        }
    }

    protected virtual void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    public event PropertyChangedEventHandler PropertyChanged;
}

public class TestViewModel
{
    public ObservableCollection<TestModel> DataCollection { get; set; }
    public TestViewModel()
    {
        DataCollection = new ObservableCollection<TestModel>();
    }

    public void AddItems(Xamarin.Essentials.Contact contact)
    {
        var newItem = new TestModel { Content = contact.DisplayName };
        DataCollection.Add(newItem);
    }
}
· 8
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

public void AddItems(Xamarin.Essentials.Contact contact) {
var newItem = new TestModel { Content = contact.Phones.ToString() };
DataCollection.Add(newItem);
}

i added this code to take mobile number but i could n't how i can take the phonenumber ?


0 Votes 0 ·

You could get the collection of phone numbers of the contact using the Contact.Phones property.

var phonesList = contact.Phones;
0 Votes 0 ·

81488-whatsapp-image-2021-03-25-at-31727-pm.jpeg




I added this image here .

I want name in first row and mobile number in second row.

I dont want both in same row


0 Votes 0 ·
Show more comments

How i can multiselect the contacts from my contact list ?

as of now you selecting one by one contact i want to select atleast 5 or 10 contacts at same time how i can achieve that ?

0 Votes 0 ·
Show more comments
JarvanZhang-MSFT avatar image
0 Votes"
JarvanZhang-MSFT answered JarvanZhang-MSFT commented

Hello,​

Welcome to our Microsoft Q&A platform!

Try to add a bool property in the model class. Then set binding for the IsChecked property of the CheckBox and the binding Mode to TwoWay. Add an ObservableCollection<TestModel> property to set data binding for the second page.

Update

Create a public static ViewModel property in the App class to set BindingContext for the two pages.

public partial class App : Application
{
    public static TestViewModel viewModel;
    public App()
    {
        InitializeComponent();

        viewModel = new TestViewModel();
        MainPage = new NavigationPage(new MainPage());
    }
    ...
}

The first page which loads all the contacts and performs the navigation.

<ContentPage ...x:Class="TestApplication_5.MainPage">

    <StackLayout>
        <Button Text="Add contacts" Clicked="LoadAllContacts_Clicked"/>
        <Button Text="Edit contacts" Clicked="EditContacts_Clicked"/>

        <ListView x:Name="listview" HasUnevenRows="True" ItemsSource="{Binding DataCollection}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout>
                            <Label Text="{Binding Content}"/>
                            <Label Text="{Binding PhoneNumber, StringFormat='PhoneNumber is {0}'}"/>
                            <CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay}"/>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>
</ContentPage>

public partial class MainPage : ContentPage
{
    TestViewModel viewModel;
    public MainPage()
    {
        InitializeComponent();

        viewModel = App.viewModel;
        BindingContext = viewModel;
    }

    private async void LoadAllContacts_Clicked(object sender, EventArgs e)
    {
        var contacts = await Contacts.GetAllAsync();
        foreach (var item in contacts)
        {
            viewModel.AddItems(item);
        }
    }

    private void EditContacts_Clicked(object sender, EventArgs e)
    {
        var collection = viewModel.DataCollection;
        foreach (var item in collection)
        {
            if (item.IsSelected)
            {
                viewModel.EditedDataCollection.Add(item);
            }
        }
        Navigation.PushAsync(new ContactsListPage());
    }
}

The second page that displays the edited contacts.

//page.xaml
<ContentPage ... x:Class="TestApplication_5.ContactsListPage">
    <ContentPage.Content>
        <StackLayout>
            <ListView ItemsSource="{Binding EditedDataCollection}">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <StackLayout>
                                <Label Text="{Binding Content}"/>
                                <Label Text="{Binding PhoneNumber, StringFormat='PhoneNumber is {0}'}"/>
                            </StackLayout>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

//page.xaml.cs
public partial class ContactsListPage : ContentPage
{
    public ContactsListPage()
    {
        InitializeComponent();

        BindingContext = App.viewModel;
    }
}

Model class and ViewModel class

public class TestModel : INotifyPropertyChanged
{
    private string content;
    public string Content
    {
        get
        {
            return content;
        }
        set
        {
            if (content != value)
            {
                content = value;
                NotifyPropertyChanged();
            }
        }
    }

    private string phoneNumber;
    public string PhoneNumber
    {
        get
        {
            return phoneNumber;
        }
        set
        {
            if (phoneNumber != value)
            {
                phoneNumber = value;
                NotifyPropertyChanged();
            }
        }
    }

    private bool isSelected;
    public bool IsSelected
    {
        get
        {
            return isSelected;
        }
        set
        {
            if (isSelected != value)
            {
                isSelected = value;
                NotifyPropertyChanged();
            }
        }
    }

    protected virtual void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    public event PropertyChangedEventHandler PropertyChanged;
}

public class TestViewModel
{
    public ObservableCollection<TestModel> DataCollection { get; set; }

    public ObservableCollection<TestModel> EditedDataCollection { get; set; }

    public TestViewModel()
    {
        DataCollection = new ObservableCollection<TestModel>();
        EditedDataCollection = new ObservableCollection<TestModel>();
    }

    public void AddItems(Xamarin.Essentials.Contact contact)
    {
        var phonesList = contact.Phones;

        var newItem = new TestModel { Content = contact.DisplayName, PhoneNumber = phonesList[0].PhoneNumber };

        DataCollection.Add(newItem);
    }
}


Best Regards,

Jarvan Zhang



If the response is helpful, please click "Accept Answer" and upvote it.

Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


· 16
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Can you send me the solution file . I faced an error . Could not get all contacts

0 Votes 0 ·

What error did you face? Please post the related details or share a screenshot to desribe that.

0 Votes 0 ·

Which page I need to add what code please mention clearly . I don’t know page 2 which code and page 1 which code .

Please mention it clearly or send me the full page code



0 Votes 0 ·
Show more comments