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

Vasanthakumar M 251 Reputation points
2021-03-24T11:56:17.423+00:00

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

How to achieve it ?

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,378 questions
{count} votes

2 answers

Sort by: Most helpful
  1. JarvanZhang 23,966 Reputation points
    2021-03-25T08:36:13.193+00:00

    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);
        }
    }
    

  2. JarvanZhang 23,966 Reputation points
    2021-03-26T08:32:03.447+00:00

    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.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.