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