Introduction:
In this article we can learn how to fetch mobile contacts using Xamarin.Mobile in Xamarin.Forms.
Requirements:
Step 2:
In right side SearchBox, search for "Xamarin.Mobile", we can get the Xamarin.Mobile component right side panel. Double click on component to install on our app.
4. How to create CheckBox to select contact from contact list?
Portable Class Library(PCL)
CheckBox.xaml.cs
5. How to Bind contact list to the UI?
5.1. Displaying Contacts:
1) BaseModel.cs
2) ContactDetails.cs
Note: IsVisible, IsSelected properties for CheckBox purpose.
Views:
ContactsListPage.xaml
ContactsListPage.xaml.cs
View Models:
ContactsListPageViewModel.cs
This ViewModel is used to display the ContactsList.
5.2. Select Contacts:
Views:
SelectedContactsPage.xaml
6. How to change the NavigationBar Background and TextColor?
App.xaml.cs
In this article we can learn how to fetch mobile contacts using Xamarin.Mobile in Xamarin.Forms.
Requirements:
- This article's source code is prepared by using Visual Studio. It is better to install the latest Visual Studio updates from here.
- This article is prepared on a MAC machine.
- This sample project is in Xamarin.Forms of PCL project.
- This sample app is targeted for Android, iOS. And tested for Android & iOS.
This article can explain you below topics:
- How to create Xamarin.Forms PCL project with Visual studio for Mac?
- How to add Components to the Xamarin.Forms App?
- How to get mobile contacts using Xamarin.Mobile in Xamarin.Forms?
- How to create CheckBox to select contact from contact list?
- How to bind contact list to the UI?
- How to change the NavigationBar Background and TextColor?
1. How to create Xamarin.Forms PCL project with Visual studio for Mac?
The creation of a Xamarin.Forms project is very simple in Visual Studio for Mac. It will create three projects,
The creation of a Xamarin.Forms project is very simple in Visual Studio for Mac. It will create three projects,
- Shared Code
- Xamarin.Android
- Xamarin.iOS
The Mac system with Visual Studio for Mac doesn't support Windows projects (UWP, Windows, Windows Phone).
The following steps will show you how to create Xamarin.Forms projects on a Mac system using Visual Studio.
First, open Visual Studio for Mac. Then click on New Project.
After that, we need to select whether you're doing Xamarin.Forms or Xamarin.Android or Xamarin.iOS project. If we want to create Xamarin.Forms project, just follow the below screenshot.The following steps will show you how to create Xamarin.Forms projects on a Mac system using Visual Studio.
First, open Visual Studio for Mac. Then click on New Project.
Then, we have to give the app name; i.e., GetContactsDemo.
Note
In the above screen, under Shared Code, select Portable Class Library or use Shared Library.
Then, click on Next button and the following screenshot will be displayed. In that screen, we have to browse the file path where we want to save that application on our PC.
Then, click on Next button and the following screenshot will be displayed. In that screen, we have to browse the file path where we want to save that application on our PC.
After clicking on the create button it will create the GetContactsDemo Xamarin.Forms project like below.
And the project structure will be,
- GetContactsDemo: It is for Shared Code
- GetContactsDemo.Droid: It is for Android.
- GetContactsDemo.iOS: It is for iOS
2. How to add Components to the Xamarin.Forms App?
Now we are installing Xamarin.Mobile component on Xamarin.Android and Xamarin.iOS projects for getting mobile contacts.
Step 1:
First Right Click on Components folder and click on get more Components.
Step 2:
In right side SearchBox, search for "Xamarin.Mobile", we can get the Xamarin.Mobile component right side panel. Double click on component to install on our app.
3. How to get mobile contacts using Xamarin.Mobile in Xamarin.Forms?
Portable Class Library(PCL)
Create an interface IContactService inside the DependencyServices folder and having method declaration of GetAllContacts.
IContactService.cs
- using System.Collections.Generic;
- using System.Threading.Tasks;
- using GetContactsDemo.Models;
- namespace GetContactsDemo.DependencyServices
- {
- public interface IContactService
- {
- Task<IEnumerable<ContactDetails>> GetAllContacts();
- }
- }
Xamarin.Android
First we need to add permission in Manifest file for accessing contacts.
AndroidManifest.xml
Create a class ContactService and need to implement GetAllContacts method like below.
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.NavigateToLocation.GetContactsDemo">
- <uses-sdk android:minSdkVersion="15" />
- <uses-permission android:name="android.permission.READ_CONTACTS" />
- <application android:label="GetContactsDemo">
- </application>
- </manifest>
Create a class ContactService and need to implement GetAllContacts method like below.
ContactService.cs
- using System;
- using System.Collections.Generic;
- using System.Threading.Tasks;
- using Xamarin.Forms;
- using System.Linq;
- using GetContactsDemo.Droid;
- using GetContactsDemo.DependencyServices;
- using GetContactsDemo.Models;
- [assembly: Dependency(typeof(ContactService))]
- namespace GetContactsDemo.Droid{
- public class ContactService : IContactService{
- readonly Xamarin.Contacts.AddressBook _addressBook;
- static IEnumerable<ContactDetails> _contactsList;
- public ContactService(){
- _addressBook = new Xamarin.Contacts.AddressBook(Forms.Context.ApplicationContext);
- }
- public async Task<IEnumerable<ContactDetails>> GetAllContacts(){
- var contacts = new List<ContactDetails>();
- await _addressBook.RequestPermission().ContinueWith(t =>{
- if (!t.Result){
- App.Current.MainPage.DisplayAlert("GetContactsDemo", "Sorry ! Permission was denied", "Ok");
- return;
- }
- foreach (var contact in _addressBook.ToList()){
- contacts.Add(new ContactDetails(){
- FirstName = contact.FirstName != null ? contact.FirstName : string.Empty,
- LastName = contact.LastName != null ? contact.LastName : string.Empty,
- DisplayName = contact.DisplayName != null ? contact.DisplayName : string.Empty,
- EmailId = contact.Emails.FirstOrDefault() != null ? contact.Emails.FirstOrDefault().Address : String.Empty,
- Number = contact.Phones.FirstOrDefault() != null ? contact.Phones.FirstOrDefault().Number : String.Empty,
- IsVisible = false
- });
- }
- });
- _contactsList = (from c in contacts orderby c.FirstName select c).ToList();
- return _contactsList;
- }
- }
- }
Xamarin.iOS
Giving permission in info.plist file for accessing contacts.
info.plist:
info.plist:
Now Create a class ContactService and need to implement GetAllContacts method like below.
ContactService.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using GetContactsDemo.iOS;
- using GetContactsDemo.DependencyServices;
- using GetContactsDemo.Models;
- [assembly: Xamarin.Forms.Dependency(typeof(ContactService))]
- namespace GetContactsDemo.iOS{
- public class ContactService : IContactService{
- private readonly Xamarin.Contacts.AddressBook _addressBook;
- private static IEnumerable<ContactDetails> _contactsList;
- public ContactService(){
- _addressBook = new Xamarin.Contacts.AddressBook();
- }
- public async Task<IEnumerable<ContactDetails>> GetAllContacts(){
- var contacts = new List<ContactDetails>();
- await _addressBook.RequestPermission().ContinueWith(t =>{
- if (!t.Result){
- App.Current.MainPage.DisplayAlert("GetContactsDemo", "Sorry ! Permission was denied", "Ok");
- return;
- }
- foreach (var contact in _addressBook.ToList()){
- contacts.Add(new ContactDetails(){
- FirstName = contact.FirstName !=null ? contact.FirstName : string.Empty,
- LastName = contact.LastName != null ? contact.LastName : string.Empty,
- DisplayName = contact.DisplayName != null ? contact.DisplayName : string.Empty,
- EmailId = contact.Emails.FirstOrDefault() != null ? contact.Emails.FirstOrDefault().Address : String.Empty,
- Number = contact.Phones.FirstOrDefault() != null ? contact.Phones.FirstOrDefault().Number : String.Empty,
- IsVisible = false//for checkbox visible
- });
- }
- });
- _contactsList = (from c in contacts orderby c.FirstName select c).ToList();
- return _contactsList;
- }
- }
- }
4. How to create CheckBox to select contact from contact list?
Portable Class Library(PCL)
Now we are creating checkbox control to select multiple contacts from contact list.
Create folder with the name CustomControls and after that right click on your newly created folder => Add => New File => Forms => Forms ContentView Xaml and name it CheckBox.
CheckBox.xaml
- <?xml version="1.0" encoding="UTF-8"?>
- <ContentView xmlns="http://xamarin.com/schemas/2014/forms"
- xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
- x:Class="GetContactsDemo.CustomControls.CheckBox">
- <ContentView.Content>
- <StackLayout Orientation="Horizontal"
- x:Name="mainContainer"
- HorizontalOptions="FillAndExpand"
- VerticalOptions="FillAndExpand"
- Padding="0"
- Spacing="5">
- <AbsoluteLayout HorizontalOptions="Center"
- VerticalOptions="Center"
- WidthRequest="20"
- HeightRequest="20"
- x:Name="imageContainer">
- <Image Source="{Binding CheckedBackgroundImageSource}"
- x:Name="checkedBackground"
- Aspect="AspectFit"
- AbsoluteLayout.LayoutBounds="0.5, 0.5, 1, 1"
- AbsoluteLayout.LayoutFlags="All"
- Opacity="0"
- InputTransparent="True"/>
- <Image Source="{Binding BorderImageSource}"
- x:Name="borderImage"
- Aspect="AspectFit"
- AbsoluteLayout.LayoutBounds="0.5, 0.5, 1, 1"
- AbsoluteLayout.LayoutFlags="All"
- InputTransparent="True"/>
- <Image Source="{Binding CheckmarkImageSource}"
- x:Name="checkedImage"
- Aspect="AspectFit"
- AbsoluteLayout.LayoutBounds="0.5, 0.5, 1, 1"
- AbsoluteLayout.LayoutFlags="All"
- Opacity="0"
- InputTransparent="True"/>
- </AbsoluteLayout>
- <Label x:Name="controlLabel"
- HorizontalOptions="FillAndExpand"
- VerticalOptions="FillAndExpand"
- HorizontalTextAlignment="Start"
- VerticalTextAlignment="Center"
- Text="{Binding Title}"
- Style="{Binding LabelStyle}"
- InputTransparent="True"/>
- </StackLayout>
- </ContentView.Content>
- </ContentView>
Now adding below Bindable properties for our CheckBox control in code behind and animation properties.
- TitleProperty: To bind tile of check box.
- LabelStyleProperty: To to set style to Title label.
- IsCheckedProperty: To maintain CheckBox states for check or uncheck.
- BorderImageSourceProperty: To set Border image for CheckBox.
- CheckedBackgroundImageSourceProperty:To set Background image for CheckBox.
- CheckMarkImageSourceProperty: To set CheckMark image for CheckBox.
- CheckedChangedCommandProperty: To make interaction with checkbox when user tap on it's main container.
CheckBox.xaml.cs
- using Xamarin.Forms;
- using Xamarin.Forms.Xaml;
- namespace GetContactsDemo.CustomControls{
- [XamlCompilation(XamlCompilationOptions.Compile)]
- public partial class CheckBox : ContentView{
- public CheckBox(){
- InitializeComponent();
- controlLabel.BindingContext = this;
- checkedBackground.BindingContext = this;
- checkedImage.BindingContext = this;
- borderImage.BindingContext = this;
- mainContainer.GestureRecognizers.Add(new TapGestureRecognizer(){
- Command = new Command(tapped)
- });
- }
- public static readonly BindableProperty BorderImageSourceProperty = BindableProperty.Create(nameof(BorderImageSource), typeof(string), typeof(CheckBox), "", BindingMode.OneWay);
- public static readonly BindableProperty CheckedBackgroundImageSourceProperty = BindableProperty.Create(nameof(CheckedBackgroundImageSource), typeof(string), typeof(CheckBox), "", BindingMode.OneWay);
- public static readonly BindableProperty CheckmarkImageSourceProperty = BindableProperty.Create(nameof(CheckmarkImageSource), typeof(string), typeof(CheckBox), "", BindingMode.OneWay);
- public static readonly BindableProperty IsCheckedProperty = BindableProperty.Create(nameof(IsChecked), typeof(bool), typeof(CheckBox), false, BindingMode.TwoWay, propertyChanged: checkedPropertyChanged);
- public static readonly BindableProperty TitleProperty = BindableProperty.Create(nameof(Title), typeof(string), typeof(CheckBox), "", BindingMode.OneWay);
- public static readonly BindableProperty CheckedChangedCommandProperty = BindableProperty.Create(nameof(CheckedChangedCommand), typeof(Command), typeof(CheckBox), null, BindingMode.OneWay);
- public static readonly BindableProperty LabelStyleProperty = BindableProperty.Create(nameof(LabelStyle), typeof(Style), typeof(CheckBox), null, BindingMode.OneWay);
- public string BorderImageSource{
- get { return (string)GetValue(BorderImageSourceProperty); }
- set { SetValue(BorderImageSourceProperty, value); }
- }
- public string CheckedBackgroundImageSource{
- get { return (string)GetValue(CheckedBackgroundImageSourceProperty); }
- set { SetValue(CheckedBackgroundImageSourceProperty, value); }
- }
- public string CheckmarkImageSource{
- get { return (string)GetValue(CheckmarkImageSourceProperty); }
- set { SetValue(CheckmarkImageSourceProperty, value); }
- }
- public bool IsChecked{
- get { return (bool)GetValue(IsCheckedProperty); }
- set { SetValue(IsCheckedProperty, value); }
- }
- public string Title{
- get { return (string)GetValue(TitleProperty); }
- set { SetValue(TitleProperty, value); }
- }
- public Command CheckedChangedCommand{
- get { return (Command)GetValue(CheckedChangedCommandProperty); }
- set { SetValue(CheckedChangedCommandProperty, value); }
- }
- public Style LabelStyle{
- get { return (Style)GetValue(LabelStyleProperty); }
- set { SetValue(LabelStyleProperty, value); }
- }
- public Label ControlLabel{
- get { return controlLabel; }
- }
- static void checkedPropertyChanged(BindableObject bindable, object oldValue, object newValue){
- ((CheckBox)bindable).ApplyCheckedState();
- }
- /// <summary>
- /// Handle chackox tapped action
- /// </summary>
- void tapped(){
- IsChecked = !IsChecked;
- ApplyCheckedState();
- }
- /// <summary>
- /// Reflect the checked event change on the UI
- /// with a small animation
- /// </summary>
- /// <param name="isChecked"></param>
- ///
- void ApplyCheckedState(){
- Animation storyboard = new Animation();
- Animation fadeAnim = null;
- Animation checkBounceAnim = null;
- Animation checkFadeAnim = null;
- double fadeStartVal = 0;
- double fadeEndVal = 1;
- double scaleStartVal = 0;
- double scaleEndVal = 1;
- Easing checkEasing = Easing.CubicIn;
- if (IsChecked){
- checkedImage.Scale = 0;
- fadeStartVal = 0;
- fadeEndVal = 1;
- scaleStartVal = 0;
- scaleEndVal = 1;
- checkEasing = Easing.CubicIn;
- }
- else{
- fadeStartVal = 1;
- fadeEndVal = 0;
- scaleStartVal = 1;
- scaleEndVal = 0;
- checkEasing = Easing.CubicOut;
- }
- fadeAnim = new Animation(
- callback: d => checkedBackground.Opacity = d,
- start: fadeStartVal,
- end: fadeEndVal,
- easing: Easing.CubicOut
- );
- checkFadeAnim = new Animation(
- callback: d => checkedImage.Opacity = d,
- start: fadeStartVal,
- end: fadeEndVal,
- easing: checkEasing
- );
- checkBounceAnim = new Animation(
- callback: d => checkedImage.Scale = d,
- start: scaleStartVal,
- end: scaleEndVal,
- easing: checkEasing
- );
- storyboard.Add(0, 0.6, fadeAnim);
- storyboard.Add(0, 0.6, checkFadeAnim);
- storyboard.Add(0.4, 1, checkBounceAnim);
- storyboard.Commit(this, "checkAnimation", length: 600);
- if (CheckedChangedCommand != null && CheckedChangedCommand.CanExecute(this))
- CheckedChangedCommand.Execute(this);
- }
- }
- }
5. How to Bind contact list to the UI?
5.1. Displaying Contacts:
Models:
In Models we are going to create two classes BaseModel, ContactDetails.
1) BaseModel.cs
Here we are implementing INotifyPropertychanged, In future this class will useful for ContactListPageViewModel, SelectedContactsViewModel.
- using System.ComponentModel;
- namespace GetContactsDemo.Models
- {
- public class BaseModel : INotifyPropertyChanged
- {
- public event PropertyChangedEventHandler PropertyChanged;
- protected virtual void OnPropertyChanged(string propertyName)
- {
- if (PropertyChanged != null)
- {
- PropertyChanged(this,
- new PropertyChangedEventArgs(propertyName));
- }
- }
- }
- }
2) ContactDetails.cs
This class properties will useful to get contact data.
- namespace GetContactsDemo.Models{
- public class ContactDetails : BaseModel{
- public string FirstName { get; set; }
- public string LastName { get; set; }
- public string DisplayName { get; set; }
- public string EmailId { get; set; }
- public string Picture { get; set; }
- public string Number { get; set; }
- bool _isVisible;
- public bool IsVisible {
- get {
- return _isVisible;
- }
- set {
- _isVisible = value;
- OnPropertyChanged("IsVisible");
- }
- }
- bool _isSelected;
- public bool IsSelected {
- get {
- return _isSelected;
- }
- set {
- _isSelected = value;
- OnPropertyChanged("IsSelected");
- }
- }
- }
- }
Note: IsVisible, IsSelected properties for CheckBox purpose.
Views:
Create your own XAML page named ContactListPage.xaml inside the Views folder and make sure to refer to "CheckBox" class in XAML by declaring a namespace for its location and using the namespace prefix on the control element.
ContactsListPage.xaml
- <?xml version="1.0" encoding="UTF-8"?>
- <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
- xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
- x:Class="GetContactsDemo.Views.ContactsListPage"
- BackgroundColor="#533F95"
- xmlns:ctrls="clr-namespace:GetContactsDemo.CustomControls"
- Title="Contacts">
- <ContentPage.ToolbarItems>
- <ToolbarItem
- Text ="Select"
- Priority="0"
- Order="Primary"
- Command="{Binding SelectContactCommand}"/>
- </ContentPage.ToolbarItems>
- <StackLayout x:Name="stackPanel"
- VerticalOptions="FillAndExpand"
- Spacing="0">
- <SearchBar
- TextColor="#533F95"
- Text="{Binding SearchString}"
- CancelButtonColor="#533F95"
- Placeholder="Search"
- PlaceholderColor="#533F95"
- BackgroundColor="White"/>
- <ListView x:Name="listView"
- BackgroundColor="#533F95"
- SeparatorColor="Silver" HasUnevenRows="true"
- SelectedItem="{Binding SelectedContact, Mode=TwoWay}"
- ItemsSource="{Binding SearchContactList}">
- <ListView.ItemTemplate>
- <DataTemplate>
- <ViewCell>
- <StackLayout Padding="20"
- Orientation="Horizontal">
- <Label Text="{Binding DisplayName}"
- VerticalTextAlignment="Center"
- TextColor="White" FontSize="20"/>
- <ctrls:CheckBox x:Name="cbUS"
- IsVisible="{Binding IsVisible}"
- IsChecked="{Binding IsSelected}"
- BorderImageSource="check_box_border.png"
- CheckedBackgroundImageSource="checked_bg.png"
- CheckmarkImageSource="check_mark.png" HorizontalOptions="EndAndExpand"/>
- </StackLayout>
- </ViewCell>
- </DataTemplate>
- </ListView.ItemTemplate>
- </ListView>
- <StackLayout Padding="20">
- <Button Text="Go" HorizontalOptions="FillAndExpand"
- Command="{Binding NavigationCommand}"
- BackgroundColor="White"
- TextColor="#533F95"/>
- </StackLayout>
- </StackLayout>
- </ContentPage>
The "ctrls" namespace prefix can be named anything. However, the clr-namespace and assembly values must match the details of the CheckBox class. Once the namespace is declared the prefix is used to reference the custom control.
ContactsListPage.xaml.cs
Make BindingContext in code behind with ContactListPageViewModel.
- using System.Linq;
- using GetContactsDemo.CustomControls;
- using GetContactsDemo.Models;
- using GetContactsDemo.ViewModels;
- using Xamarin.Forms;
- namespace GetContactsDemo.Views
- {
- public partial class ContactsListPage : ContentPage
- {
- public ContactsListPage()
- {
- InitializeComponent();
- BindingContext = new ContactsListViewModel(Navigation);
- listView.ItemSelected += (sender, e) =>
- {
- var itemSelected = e.SelectedItem as ContactDetails;
- if (itemSelected == null)
- {
- return;
- }
- ((ListView)sender).SelectedItem = null;
- };
- }
- }
- }
View Models:
ContactsListPageViewModel.cs
This ViewModel is used to display the ContactsList.
Properties:
- ContactList
- SearchContactList
- SearchString
Commands:
- SelectedContactCommand
- NavigationCommand
- using System.Collections.Generic;
- using System.Collections.ObjectModel;
- using System.Linq;
- using System.Windows.Input;
- using GetContactsDemo.DependencyServices;
- using GetContactsDemo.Models;
- using Xamarin.Forms;
- namespace GetContactsDemo.ViewModels
- {
- public class ContactsListViewModel : BaseModel{
- public ICommand SelectContactCommand { get; private set; }
- public ICommand NavigationCommand { get; private set; }
- public INavigation _navigation;
- ObservableCollection<ContactDetails> _contactList;
- public ObservableCollection<ContactDetails> ContactList{
- get {
- return _contactList;
- }
- set {
- _contactList = value;
- OnPropertyChanged("ContactList");
- }
- }
- IEnumerable<ContactDetails> _searchContactList;
- public IEnumerable<ContactDetails> SearchContactList{
- get{
- return _searchContactList;
- }
- set{
- _searchContactList = value;
- OnPropertyChanged("SearchContactList");
- }
- }
- string _searchString;
- public string SearchString{
- get{
- return _searchString;
- }
- set{
- _searchString = value;
- SearchContactList =
- string.IsNullOrEmpty(value) ? ContactList :
- ContactList.Where(i => i.DisplayName.ToLower().Contains(value.ToLower()));
- OnPropertyChanged("SearchString");
- }
- }
- public ContactsListViewModel(INavigation navigation) {
- _navigation = navigation;
- GetContacts();
- SelectContactCommand = new Command(() => SelectContact());
- NavigationCommand = new Command(() => Navigation_Page());
- }
- public async void GetContacts(){
- var _contactService = DependencyService.Get<IContactService>();
- var contacts = await _contactService.GetAllContacts();
- ContactList = new ObservableCollection<ContactDetails>(contacts);
- SearchContactList = ContactList;
- }
- void SelectContact(){
- foreach (var item in ContactList){
- item.IsVisible = true;
- }
- }
- void Navigation_Page(){
- var selectedContactsList = ContactList.Where(x => x.IsSelected == true).ToList();
- if (selectedContactsList.Count > 0){
- _navigation.PushAsync(new Views.SelectedContactsPage(selectedContactsList));
- }
- else{
- App.Current.MainPage.DisplayAlert("GetContactsDemo", "Please select atleast one contact", "Ok");
- }
- }
- }
- }
5.2. Select Contacts:
Views:
Create your own XAML page named SelectContctsPage.xaml inside the Views folder. And this will display selected contacts from ContactListPage.
SelectedContactsPage.xaml
- <?xml version="1.0" encoding="UTF-8"?>
- <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
- xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
- x:Class="GetContactsDemo.Views.SelectedContactsPage"
- Title="Selected Contacts">
- <StackLayout x:Name="stackPanel"
- VerticalOptions="FillAndExpand"
- Spacing="0">
- <ListView x:Name="listView"
- BackgroundColor="#533F95"
- SeparatorColor="Silver"
- HasUnevenRows="true"
- ItemsSource="{Binding SelectedContactList}">
- <ListView.ItemTemplate>
- <DataTemplate>
- <ViewCell>
- <StackLayout Padding="10">
- <Label Text="{Binding DisplayName}"
- VerticalTextAlignment="Center"
- TextColor="White"
- FontSize="20"/>
- <Label Text="{Binding Number}"
- VerticalTextAlignment="Center"
- TextColor="White"
- FontSize="20"/>
- </StackLayout>
- </ViewCell>
- </DataTemplate>
- </ListView.ItemTemplate>
- </ListView>
- </StackLayout>
- </ContentPage>
SelectedContactsPage.xaml.cs
Make BindingContext in code behind with SelectedContactsViewModel.
- using System.Collections.Generic;
- using GetContactsDemo.Models;
- using GetContactsDemo.ViewModels;
- using Xamarin.Forms;
- namespace GetContactsDemo.Views
- {
- public partial class SelectedContactsPage : ContentPage
- {
- public SelectedContactsPage(List<ContactDetails> SelectedList)
- {
- InitializeComponent();
- BindingContext = new SelectedContactsViewModel(SelectedList);
- }
- }
- }
ViewModel:
SelectedContactsPageViewModel.cs
This viewmodel is used to display the selected contact list.
SelectedContactsPageViewModel.cs
This viewmodel is used to display the selected contact list.
Properties:
- SelectedContactList
- using System.Collections.Generic;
- using System.Collections.ObjectModel;
- using GetContactsDemo.Models;
- namespace GetContactsDemo.ViewModels{
- public class SelectedContactsViewModel : BaseModel{
- private ObservableCollection<ContactDetails> _selectedContactList;
- public ObservableCollection<ContactDetails> SelectedContactList{
- get {
- return _selectedContactList;
- }
- set {
- _selectedContactList = value;
- OnPropertyChanged("SelectedContactList");
- }
- }
- public SelectedContactsViewModel(List<ContactDetails> SelectedList) {
- SelectedContactList = new ObservableCollection<ContactDetails>(SelectedList);
- }
- }
- }
6. How to change the NavigationBar Background and TextColor?
In App.cs we are changing NavigationBar Background and TextColor.
App.xaml.cs
- using Xamarin.Forms;
- namespace GetContactsDemo
- {
- public partial class App : Application
- {
- public App()
- {
- InitializeComponent();
- MainPage = new NavigationPage(new Views.ContactsListPage()){
- BarBackgroundColor = Color.FromRgb(153,49,45),
- BarTextColor=Color.White
- };
- }
- protected override void OnStart()
- {
- // Handle when your app start
- }
- protected override void OnSleep()
- {
- // Handle when your app sleeps
- }
- protected override void OnResume()
- {
- // Handle when your app resumes
- }
- }
- }
No comments:
Post a Comment