0% found this document useful (0 votes)
334 views1,756 pages

Getting Started with Xamarin.Forms Guide

This document provides an overview of the requirements for developing applications with Xamarin.Forms, including supported target platforms, minimum platform versions, and development environment requirements. It discusses that Xamarin.Forms supports building apps for iOS, Android, and UWP, with additional platform support under development. The minimum Android API level is 15, and iOS 8 or higher is required. Visual Studio or Visual Studio for Mac is needed for development.

Uploaded by

Cepi Supriadi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
334 views1,756 pages

Getting Started with Xamarin.Forms Guide

This document provides an overview of the requirements for developing applications with Xamarin.Forms, including supported target platforms, minimum platform versions, and development environment requirements. It discusses that Xamarin.Forms supports building apps for iOS, Android, and UWP, with additional platform support under development. The minimum Android API level is 15, and iOS 8 or higher is required. Visual Studio or Visual Studio for Mac is needed for development.

Uploaded by

Cepi Supriadi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1756

Contents

Xamarin.Forms
Getting Started
Requirements
Hello, Xamarin.Forms
Part 1: Quickstart
Part 2: Deep Dive
Hello, Xamarin.Forms Multiscreen
Part 1: Quickstart
Part 2: Deep Dive
Introduction to Xamarin.Forms
XAML
XAML Basics
Part 1. Getting Started with XAML
Part 2. Essential XAML Syntax
Part 3. XAML Markup Extensions
Part 4. Data Binding Basics
Part 5. From Data Bindings to MVVM
XAML Compilation
Live Reload
XAML Previewer
XAML Namespaces
XAML Markup Extensions
Consuming XAML Markup Extensions
Creating XAML Markup Extensions
Field Modifiers
Passing Arguments
Bindable Properties
Attached Properties
Resource Dictionaries
XAML Standard (Preview)
Controls
Application Fundamentals
Accessibility
Setting Accessibility Values on User Interface Elements
App Class
App Lifecycle
Behaviors
Introduction
Attached Behaviors
Xamarin.Forms Behaviors
Reusable Behaviors
EffectBehavior
EventToCommandBehavior
Custom Renderers
Introduction
Renderer Base Classes and Native Controls
Customizing an Entry
Customizing a ContentPage
Customizing a Map
Customizing a Map Pin
Highlighting a Circular Area on a Map
Highlighting a Region on a Map
Highlighting a Route on a Map
Customizing a ListView
Customizing a ViewCell
Implementing a View
Implementing a HybridWebView
Implementing a Video Player
Creating the Platform Video Players
Playing a Web Video
Binding Video Sources to the Player
Loading Application Resource Videos
Accessing the Device's Video Library
Custom Video Transport Controls
Custom Video Positioning
Data Binding
Basic Bindings
Binding Mode
String Formatting
Binding Path
Binding Value Converters
The Command Interface
DependencyService
Introduction
Implementing Text-to-Speech
Checking Device Orientation
Checking Battery Status
Picking from the Photo Library
Effects
Introduction
Effect Creation
Passing Parameters
Parameters as CLR Properties
Parameters as Attached Properties
Invoking Events
Files
Gestures
Tap
Pinch
Pan
Localization
String and Image Localization
Right-to-Left Localization
Local Databases
MessagingCenter
Navigation
Hierarchical Navigation
TabbedPage
CarouselPage
MasterDetailPage
Modal Pages
Displaying Pop-Ups
Templates
Control Templates
Introduction
Control Template Creation
Template Bindings
Data Templates
Introduction
Data Template Creation
Data Template Selection
Triggers
User Interface
Animation
Simple Animations
Easing Functions
Custom Animations
BoxView
Button
Colors
Controls Reference
Pages
Layouts
Views
Cells
DataPages
Getting Started
Controls Reference
DatePicker
Graphics
Using CocosSharp in Xamarin.Forms
Using SkiaSharp in Xamarin.Forms
SkiaSharp Drawing Basics
Drawing a Simple Circle
Integrating with Xamarin.Forms
Pixels and Device-Independent Units
Basic Animation
Integrating Text and Graphics
Bitmap Basics
SkiaSharp Lines and Paths
Lines and Stroke Caps
Path Basics
The Path Fill Types
Polylines and Parametric Equations
Dots and Dashes
Finger Painting
SkiaSharp Transforms
The Translate Transform
The Scale Transform
The Rotate Transform
The Skew Transform
Matrix Transforms
Touch Manipulations
Non-Affine Transforms
3D Rotation
SkiaSharp Curves and Paths
Three Ways to Draw an Arc
Three Types of Bézier Curves
SVG Path Data
Clipping with Paths and Regions
Path Effects
Paths and Text
Path Information and Enumeration
SkiaSharp Bitmaps
Displaying Bitmaps
Creating and Drawing on Bitmaps
Cropping Bitmaps
Segmented Display of Bitmaps
Saving Bitmaps to Files
Accessing Bitmap Pixel Bits
Animating Bitmaps
Using UrhoSharp in Xamarin.Forms
Images
Layouts
StackLayout
AbsoluteLayout
RelativeLayout
Grid
FlexLayout
ScrollView
LayoutOptions
Margin and Padding
Device Orientation
Tablet & Desktop
Creating a Custom Layout
Layout Compression
ListView
Data Sources
Cell Appearance
List Appearance
Interactivity
Performance
Maps
Picker
Setting a Picker's ItemsSource Property
Adding Data to a Picker's Items Collection
Slider
Styles
Styling Xamarin.Forms Apps using XAML Styles
Introduction
Explicit Styles
Implicit Styles
Global Styles
Style Inheritance
Dynamic Styles
Device Styles
Styling Xamarin.Forms Apps using Cascading Style Sheets (CSS)
TableView
Text
Label
Entry
Editor
Fonts
Styles
Themes
Light Theme
Dark Theme
Creating a Custom Theme
Visual State Manager
WebView
Platform Features
Android
Android
AppCompat & Material Design
Application Indexing and Deep Linking
Device Class
iOS
Formatting
GTK#
Mac
Native Forms
Native Views
Native Views in XAML
Native Views in C#
Platform Specifics
Consuming Platform-Specifics
iOS
Android
Windows
Creating Platform-Specifics
Plugins
Tizen
Windows
Setup
WPF
Xamarin.Essentials
Getting Started
Accelerometer
App Information
Battery
Clipboard
Compass
Connectivity
Data Transfer
Device Display Information
Device Information
Email
File System Helpers
Flashlight
Geocoding
Geolocation
Gyroscope
Magnetometer
Main Thread
Open Browser
Orientation Sensor
Phone Dialer
Power
Preferences
Screen Lock
Secure Storage
SMS
Text-to-Speech
Version Tracking
Vibrate
Troubleshooting
Data & Cloud Services
Understanding the Sample
Consuming Web Services
ASMX
WCF
REST
Azure Mobile Apps
Authenticating Access to Web Services
REST
OAuth
Azure Mobile Apps
Azure Active Directory B2C
Integrating Azure Active Directory B2C with Azure Mobile Apps
Synchronizing Data with Web Services
Azure Mobile Apps
Sending Push Notifications
Azure
Storing Files in the Cloud
Azure Storage
Searching Data in the Cloud
Azure Search
Storing Data in a Document Database
Consuming an Azure Cosmos DB Document Database
Authenticating Users with an Azure Cosmos DB Document Database
Adding Intelligence with Cognitive Services
Speech Recognition
Spell Check
Text Translation
Emotion Recognition
Deployment & Testing
Performance
Xamarin.UITest and Test Cloud
Advanced Concepts and Internals
Fast Renderers
.NET Standard
Dependency Resolution
Troubleshooting
Frequently Asked Questions
Can I update the Xamarin.Forms default template to a newer NuGet package?
Why doesn't the Visual Studio XAML designer work for Xamarin.Forms XAML
files?
Android build error: The "LinkAssemblies" task failed unexpectedly
Why does my Xamarin.Forms.Maps Android project fail with COMPILETODALVIK
: UNEXPECTED TOP-LEVEL ERROR?
Release Notes
Samples
Creating Mobile Apps with Xamarin.Forms Book
Enterprise Application Patterns eBook
Getting Started with Xamarin.Forms
6/8/2018 • 2 minutes to read • Edit Online

Xamarin.Forms is a cross-platform UI toolkit that allows developers to efficiently create native user interface
layouts that can be shared across iOS, Android, and Universal Windows Platform apps. This series introduces the
basics of Xamarin.Forms development and covers building multi-platform and multi-screen applications.
For an overview of the installation and setup practices that apply to cross-platform development, see
Xamarin.Forms Requirements and Installation.
Xamarin.Forms Quickstart

Requirements
Overview of the platform requirements for Xamarin.Forms-developed apps, and the minimum system
requirements for developing with Xamarin.Forms in Visual Studio for Mac and Visual Studio.

Hello, Xamarin.Forms
This guide provides an introduction to developing a Xamarin.Forms application using Visual Studio for Mac or
Visual Studio. Topics covered include the tools, concepts, and steps required to build and deploy a Xamarin.Forms
application.

Hello, Xamarin.Forms Multiscreen


This guide extends the previously created application by introducing navigation to a second page. Topics covered
include data binding and performing navigation.

Introduction To Xamarin.Forms
This article discusses some of the key concepts for developing applications using Xamarin.Forms, including Views
and Layouts, the ListView control, Data Binding and Navigation.

Get Started with Xamarin University


Building Your First Xamarin.Forms App with Xamarin for Visual Studio, by Xamarin University

Related Links
Free Self-Guided Learning (video)
Getting Started with Xamarin (video)
Hello, Xamarin.Forms iOS Workbook
Xamarin.Forms Requirements
5/23/2018 • 2 minutes to read • Edit Online

Platform and development system requirements for Xamarin.Forms.


Refer to the Installation article for an overview of installation and setup practices that apply across platforms.

Target platforms
Xamarin.Forms applications can be written for the following operating systems:
iOS 8 or higher
Android 4.0.3 (API 15) or higher (more details)
Windows 10 Universal Windows Platform (more details)
It is assumed that developers have familiarity with .NET Standard and Shared Projects.
Additional platform support
The status of these platforms is available on the Xamarin.Forms GitHub:
Samsung Tizen
macOS
GTK#
WPF
Platforms from earlier versions
These platforms are not supported when using Xamarin.Forms 3.0:
Windows 8.1 / Windows Phone 8.1 WinRT
Windows Phone 8 Silverlight
Android
You should have the latest Android SDK Tools and Android API platform installed. You can update to the latest
versions using the Android SDK Manager.
Additionally, the target/compile version for Android projects must be set to Use latest installed platform. However
the minimum version can be set to API 15 so you can continue to support devices that use Android 4.0.3 and
newer. These values are set in the Project Options:
Visual Studio
Visual Studio for Mac
Project Options > Application > Application Properties
Development system requirements
Xamarin.Forms apps can be developed on macOS and Windows. However, Windows and Visual Studio are
required to produce Windows versions of the app.

Mac System requirements


You can use Visual Studio for Mac to develop Xamarin.Forms apps on OS X El Capitan (10.11) or newer. To
develop iOS apps, we recommend having at least the iOS 10 SDK and Xcode 8 installed.

NOTE
Windows apps cannot be developed on macOS.

Windows system requirements


Xamarin.Forms apps for iOS and Android can be built on any Windows installation that supports Xamarin
development. This requires Visual Studio 2017 or newer running on Windows 7 or higher. A networked Mac is
required for iOS development.
Universal Windows Platform (UWP)
Developing Xamarin.Forms apps for UWP requires:
Windows 10 (Fall Creators Update recommended)
Visual Studio 2017
Windows 10 SDK
UWP projects are included in Xamarin.Forms solutions created in Visual Studio 2017, but not solutions created in
Visual Studio for Mac. You can add a Universal Windows Platform (UWP ) App to an existing Xamarin.Forms
solution at any time.
Hello, Xamarin.Forms
7/25/2018 • 2 minutes to read • Edit Online

This guide provides an introduction to developing a Xamarin.Forms application using Visual Studio for Mac or
Visual Studio, and to the fundamentals of application development using Xamarin.Forms. Topics covered include
the tools, concepts, and steps required to build and deploy a Xamarin.Forms application.
Start by reviewing the Xamarin.Forms System Requirements.

Part 1: Quickstart
The first part of this guide demonstrates how to create an application that translates an alphanumeric phone
number entered by the user into a numeric phone number, and then calls that number.

Part 2: Deep Dive


The second part of this guide reviews what has been built, to develop an understanding of the fundamentals of
how Xamarin.Forms applications work.

Related Links
Introduction to Xamarin.Forms
Debugging in Visual Studio
Visual Studio for Mac Recipes - Debugging
Free Self-Guided Learning (video)
Getting Started with Xamarin (video)
Hello, Xamarin.Forms iOS Workbook
Xamarin.Forms Quickstart
7/25/2018 • 14 minutes to read • Edit Online

This walkthrough demonstrates how to create an application that translates an alphanumeric phone number
entered by the user into a numeric phone number, and that calls the number. The final application is shown below:

Create the Phoneword application as follows:


Visual Studio
Visual Studio for Mac
1. In the Start screen, launch Visual Studio. This opens the start page:

2. In Visual Studio, click Create new project... to create a new project:


3. In the New Project dialog, click Cross-Platform, select the Mobile App (Xamarin.Forms) template, set
the Name to Phoneword, choose a suitable location for the project and click the OK button:

NOTE
Failing to name the solution Phoneword will result in numerous build errors.

4. In the New Cross Platform App dialog, click Blank App, select .NET Standard as the Code Sharing
Strategy, and click the OK button:

5. In Solution Explorer, in the Phoneword project, double-click MainPage.xaml to open it:


6. In MainPage.xaml, remove all of the template code and replace it with the following code. This code
declaratively defines the user interface for the page:

<?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="Phoneword.MainPage">
<ContentPage.Padding>
<OnPlatform x:TypeArguments="Thickness">
<On Platform="iOS" Value="20, 40, 20, 20" />
<On Platform="Android, UWP" Value="20" />
</OnPlatform>
</ContentPage.Padding>
<StackLayout>
<Label Text="Enter a Phoneword:" />
<Entry x:Name="phoneNumberText" Text="1-855-XAMARIN" />
<Button x:Name="translateButon" Text="Translate" Clicked="OnTranslate" />
<Button x:Name="callButton" Text="Call" IsEnabled="false" Clicked="OnCall" />
</StackLayout>
</ContentPage>

Save the changes to MainPage.xaml by pressing CTRL+S, and close the file.
7. In Solution Explorer, expand MainPage.xaml and double-click MainPage.xaml.cs to open it:
8. In MainPage.xaml.cs, remove all of the template code and replace it with the following code. The
OnTranslate and OnCall methods will be executed in response to the Translate and Call buttons being
clicked in the user interface, respectively:
using System;
using Xamarin.Forms;

namespace Phoneword
{
public partial class MainPage : ContentPage
{
string translatedNumber;

public MainPage ()
{
InitializeComponent ();
}

void OnTranslate (object sender, EventArgs e)


{
translatedNumber = PhonewordTranslator.ToNumber (phoneNumberText.Text);
if (!string.IsNullOrWhiteSpace (translatedNumber)) {
callButton.IsEnabled = true;
callButton.Text = "Call " + translatedNumber;
} else {
callButton.IsEnabled = false;
callButton.Text = "Call";
}
}

async void OnCall (object sender, EventArgs e)


{
if (await this.DisplayAlert (
"Dial a Number",
"Would you like to call " + translatedNumber + "?",
"Yes",
"No")) {
var dialer = DependencyService.Get<IDialer> ();
if (dialer != null)
dialer.Dial (translatedNumber);
}
}
}
}

NOTE
Attempting to build the application at this point will result in errors that will be fixed later.

Save the changes to MainPage.xaml.cs by pressing CTRL+S, and close the file.
9. In Solution Explorer, right click on the Phoneword project and select Add > New Item...:
10. In the Add New Item dialog, select Visual C# > Code > Class, name the new file PhoneTranslator, and
click the Add button:

11. In PhoneTranslator.cs, remove all of the template code and replace it with the following code. This code
will translate a phone word to a phone number:
using System.Text;

namespace Phoneword
{
public static class PhonewordTranslator
{
public static string ToNumber(string raw)
{
if (string.IsNullOrWhiteSpace(raw))
return null;

raw = raw.ToUpperInvariant();

var newNumber = new StringBuilder();


foreach (var c in raw)
{
if (" -0123456789".Contains(c))
newNumber.Append(c);
else
{
var result = TranslateToNumber(c);
if (result != null)
newNumber.Append(result);
// Bad character?
else
return null;
}
}
return newNumber.ToString();
}

static bool Contains(this string keyString, char c)


{
return keyString.IndexOf(c) >= 0;
}

static readonly string[] digits = {


"ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ"
};

static int? TranslateToNumber(char c)


{
for (int i = 0; i < digits.Length; i++)
{
if (digits[i].Contains(c))
return 2 + i;
}
return null;
}
}
}

Save the changes to PhoneTranslator.cs by pressing CTRL+S, and close the file.
12. In Solution Explorer, right click on the Phoneword project and select Add > New Item...:
13. In the Add New Item dialog, select Visual C# > Code > Interface, name the new file IDialer, and click
the Add button:

14. In IDialer.cs, remove all of the template code and replace it with the following code. This code defines a
Dial method that must be implemented on each platform to dial a translated phone number:

namespace Phoneword
{
public interface IDialer
{
bool Dial(string number);
}
}

Save the changes to IDialer.cs by pressing CTRL+S, and close the file.

NOTE
The common code for the application is now complete. Platform-specific phone dialer code will now be implemented
as a DependencyService.

15. In Solution Explorer, right click on the Phoneword.iOS project and select Add > New Item...:
16. In the Add New Item dialog, select Apple > Code > Class, name the new file PhoneDialer, and click the
Add button:

17. In PhoneDialer.cs, remove all of the template code and replace it with the following code. This code
creates the Dial method that will be used on the iOS platform to dial a translated phone number:
using Foundation;
using Phoneword.iOS;
using UIKit;
using Xamarin.Forms;

[assembly: Dependency(typeof(PhoneDialer))]
namespace Phoneword.iOS
{
public class PhoneDialer : IDialer
{
public bool Dial(string number)
{
return UIApplication.SharedApplication.OpenUrl (
new NSUrl ("tel:" + number));
}
}
}

Save the changes to PhoneDialer.cs by pressing CTRL+S, and close the file.
18. In Solution Explorer, right click on the Phoneword.Android project and select Add > New Item...:

19. In the Add New Item dialog, select Visual C# > Android > Class, name the new file PhoneDialer, and
click the Add button:
20. In PhoneDialer.cs, remove all of the template code and replace it with the following code. This code
creates the Dial method that will be used on the Android platform to dial a translated phone number:
using Android.Content;
using Android.Telephony;
using Phoneword.Droid;
using System.Linq;
using Xamarin.Forms;
using Uri = Android.Net.Uri;

[assembly: Dependency(typeof(PhoneDialer))]
namespace Phoneword.Droid
{
public class PhoneDialer : IDialer
{
public bool Dial(string number)
{
var context = MainActivity.Instance;
if (context == null)
return false;

var intent = new Intent (Intent.ActionDial);


intent.SetData (Uri.Parse ("tel:" + number));

if (IsIntentAvailable (context, intent)) {


context.StartActivity (intent);
return true;
}

return false;
}

public static bool IsIntentAvailable(Context context, Intent intent)


{
var packageManager = context.PackageManager;

var list = packageManager.QueryIntentServices (intent, 0)


.Union (packageManager.QueryIntentActivities (intent, 0));

if (list.Any ())
return true;

var manager = TelephonyManager.FromContext (context);


return manager.PhoneType != PhoneType.None;
}
}
}

Note that this code assumes that you are using the latest Android API. Save the changes to
PhoneDialer.cs by pressing CTRL+S, and close the file.
21. In Solution Explorer, in the Phoneword.Android project, double-click MainActivity.cs to open it,
remove all of the template code and replace it with the following code:
using Android.App;
using Android.Content.PM;
using Android.OS;

namespace Phoneword.Droid
{
[Activity(Label = "Phoneword", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher =
true,
ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
internal static MainActivity Instance { get; private set; }

protected override void OnCreate(Bundle bundle)


{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;

base.OnCreate(bundle);
Instance = this;
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App());
}
}
}

Save the changes to MainActivity.cs by pressing CTRL+S, and close the file.
22. In Solution Explorer, in the Phoneword.Android project, double-click Properties and select the
Android Manifest tab:

23. In the Required permissions section, enable the CALL_PHONE permission. This gives the application
permission to place a phone call:
Save the changes to the manifest by pressing CTRL+S, and close the file.
24. In Solution Explorer, right click on the Phoneword.UWP project and select Add > New Item...:

25. In the Add New Item dialog, select Visual C# > Code > Class, name the new file PhoneDialer, and click
the Add button:

26. In PhoneDialer.cs, remove all of the template code and replace it with the following code. This code
creates the Dial method, and helper methods, that will be used on the Universal Windows Platform to dial
a translated phone number:
using Phoneword.UWP;
using System;
using System.Threading.Tasks;
using Windows.ApplicationModel.Calls;
using Windows.UI.Popups;
using Xamarin.Forms;

[assembly: Dependency(typeof(PhoneDialer))]
namespace Phoneword.UWP
{
public class PhoneDialer : IDialer
{
bool dialled = false;

public bool Dial(string number)


{
DialNumber(number);
return dialled;
}

async Task DialNumber(string number)


{
var phoneLine = await GetDefaultPhoneLineAsync();
if (phoneLine != null)
{
phoneLine.Dial(number, number);
dialled = true;
}
else
{
var dialog = new MessageDialog("No line found to place the call");
await dialog.ShowAsync();
dialled = false;
}
}

async Task<PhoneLine> GetDefaultPhoneLineAsync()


{
var phoneCallStore = await PhoneCallManager.RequestStoreAsync();
var lineId = await phoneCallStore.GetDefaultLineAsync();
return await PhoneLine.FromIdAsync(lineId);
}
}
}

Save the changes to PhoneDialer.cs by pressing CTRL+S, and close the file.
27. In Solution Explorer, in the Phoneword.UWP project, right-click References, and select Add
Reference...:
28. In the Reference Manager dialog, select Universal Windows > Extensions > Windows Mobile
Extensions for UWP, and click the OK button:

29. In Solution Explorer, in the Phoneword.UWP project, double-click Package.appxmanifest:


30. In the Capabilities page, enable the Phone Call capability. This gives the application permission to place a
phone call:

Save the changes to the manifest by pressing CTRL+S, and close the file.
31. In Visual Studio, select the Build > Build Solution menu item (or press CTRL+SHIFT+B ). The application
will build and a success message will appear in the Visual Studio status bar:

If there are errors, repeat the previous steps and correct any mistakes until the application builds
successfully.
32. In Solution Explorer, right click on the Phoneword.UWP project and select Set as StartUp Project:

33. In the Visual Studio toolbar, press the Start button (the triangular button that resembles a Play button) to
launch the application:

34. In Solution Explorer, right click on the Phoneword.Android project and select Set as StartUp Project.
35. In the Visual Studio toolbar, press the Start button (the triangular button that resembles a Play button) to
launch the application inside an Android emulator.
36. If you have an iOS device and meet the Mac system requirements for Xamarin.Forms development, use a
similar technique to deploy the app to the iOS device. Alternatively, deploy the app to the iOS remote
simulator.
Note: phone calls are not supported on all the simulators.
Congratulations on completing a Xamarin.Forms application. The next topic in this guide reviews the steps that
were taken in this walkthrough to gain an understanding of the fundamentals of application development using
Xamarin.Forms.

Related Links
Accessing Native Features via the DependencyService
Phoneword (sample)
Xamarin.Forms Deep Dive
7/25/2018 • 11 minutes to read • Edit Online

In the Xamarin.Forms Quickstart, the Phoneword application was built. This article reviews what has been built to
gain an understanding of the fundamentals of how Xamarin.Forms applications work.
Visual Studio
Visual Studio for Mac

Introduction to Visual Studio


Visual Studio is a powerful IDE from Microsoft. It features a fully integrated visual designer, a text editor complete
with refactoring tools, an assembly browser, source code integration, and more. This article focuses on using some
of the basic Visual Studio features with the Xamarin plug-in.
Visual Studio organizes code into Solutions and Projects. A Solution is a container that can hold one or more
Projects. A Project can be an application, a supporting library, a test application, and more. The Phoneword
application consists of one solution containing four projects, as shown in the following screenshot.

The projects are:


Phoneword – This project is the .NET Standard library project that holds all of the shared code and shared UI.
Phoneword.Android – This project holds Android specific code and is the entry point for the Android
application.
Phoneword.iOS – This project holds iOS specific code and is the entry point for the iOS application.
Phoneword.UWP – This project holds Universal Windows Platform (UWP ) specific code and is the entry point
for the UWP application.

Anatomy of a Xamarin.Forms Application


The following screenshot shows the contents of the Phoneword .NET Standard library project in Visual Studio:
The project has a Dependencies node that contains NuGet and SDK nodes. The NuGet node contains the
Xamarin.Forms NuGet package that has been added to the project, and the SDK node contains the
NETStandard.Library metapackage that references the complete set of NuGet packages that define .NET Standard.

The project also consists of a number of files:


App.xaml – The XAML markup for the App class, which defines a resource dictionary for the application.
App.xaml.cs – The code-behind for the App class, which is responsible for instantiating the first page that will
be displayed by the application on each platform, and for handling application lifecycle events.
IDialer.cs – The IDialer interface, which specifies that the Dial method must be provided by any
implementing classes.
MainPage.xaml – The XAML markup for the MainPage class, which defines the UI for the page shown when
the application launches.
MainPage.xaml.cs – The code-behind for the MainPage class, which contains the business logic that is
executed when the user interacts with the page.
PhoneTranslator.cs – The business logic that is responsible for converting a phone word to a phone number,
which is invoked from MainPage.xaml.cs.
For more information about the anatomy of a Xamarin.iOS application, see Anatomy of a Xamarin.iOS
Application. For more information about the anatomy of a Xamarin.Android application, see Anatomy of a
Xamarin.Android Application.

Architecture and Application Fundamentals


Visual Studio
Visual Studio for Mac
A Xamarin.Forms application is architected in the same way as a traditional cross-platform application. Shared
code is typically placed in a .NET Standard library, and platform-specific applications consume the shared code.
The following diagram shows an overview of this relationship for the Phoneword application:
To maximize the reuse of startup code, Xamarin.Forms applications have a single class named App that is
responsible for instantiating the first page that will be displayed by the application on each platform, as shown in
the following code example:

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

[assembly: XamlCompilation(XamlCompilationOptions.Compile)]
namespace Phoneword
{
public partial class App : Application
{
public App()
{
InitializeComponent();
MainPage = new MainPage();
}
...
}
}

This code sets the MainPage property of the App class to a new instance of the MainPage class. In addition, the
XamlCompilation attribute turns on the XAML compiler, so that XAML is compiled directly into intermediate
language. For more information, see XAML Compilation.

Launching the Application on Each Platform


iOS
To launch the initial Xamarin.Forms page in iOS, the Phoneword.iOS project includes the AppDelegate class that
inherits from the FormsApplicationDelegate class, as shown in the following code example:

namespace Phoneword.iOS
{
[Register ("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.Init ();
LoadApplication (new App ());
return base.FinishedLaunching (app, options);
}
}
}

The FinishedLaunching override initializes the Xamarin.Forms framework by calling the Init method. This causes
the iOS -specific implementation of Xamarin.Forms to be loaded in the application before the root view controller
is set by the call to the LoadApplication method.
Android
To launch the initial Xamarin.Forms page in Android, the Phoneword.Droid project includes code that creates an
Activity with the MainLauncher attribute, with the activity inheriting from the FormsAppCompatActivity class, as
shown in the following code example:

namespace Phoneword.Droid
{
[Activity(Label = "Phoneword",
Icon = "@mipmap/icon",
Theme = "@style/MainTheme",
MainLauncher = true,
ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
internal static MainActivity Instance { get; private set; }

protected override void OnCreate(Bundle bundle)


{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;

base.OnCreate(bundle);
Instance = this;
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App());
}
}
}

The OnCreate override initializes the Xamarin.Forms framework by calling the Init method. This causes the
Android-specific implementation of Xamarin.Forms to be loaded in the application before the Xamarin.Forms
application is loaded. In addition, the MainActivity class stores a reference to itself in the Instance property. The
Instance property is known as the local context, and is referenced from the PhoneDialer class.

Universal Windows Platform


In Universal Windows Platform (UWP ) applications, the Init method that initializes the Xamarin.Forms
framework is invoked from the App class:
Xamarin.Forms.Forms.Init (e);

if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
...
}

This causes the UWP -specific implementation of Xamarin.Forms to be loaded in the application. The initial
Xamarin.Forms page is launched by the MainPage class, as demonstrated in the following code example:

namespace Phoneword.UWP
{
public sealed partial class MainPage
{
public MainPage()
{
this.InitializeComponent();
this.LoadApplication(new Phoneword.App());
}
}
}

The Xamarin.Forms application is loaded with the LoadApplication method.

NOTE
Universal Windows Platform (UWP) apps can be built with Xamarin.Forms, but only using Visual Studio on Windows.

User Interface
There are four main control groups used to create the user interface of a Xamarin.Forms application.
1. Pages – Xamarin.Forms pages represent cross-platform mobile application screens. The Phoneword
application uses the ContentPage class to display a single screen. For more information about pages, see
Xamarin.Forms Pages.
2. Layouts – Xamarin.Forms layouts are containers used to compose views into logical structures. The
Phoneword application uses the StackLayout class to arrange controls in a horizontal stack. For more
information about layouts, see Xamarin.Forms Layouts.
3. Views – Xamarin.Forms views are the controls displayed on the user interface, such as labels, buttons, and text
entry boxes. The Phoneword application uses the Label , Entry , and Button controls. For more information
about views, see Xamarin.Forms Views.
4. Cells – Xamarin.Forms cells are specialized elements used for items in a list, and describe how each item in a
list should be drawn. The Phoneword application does not make use of any cells. For more information about
cells, see Xamarin.Forms Cells.
At runtime, each control will be mapped to its native equivalent, which is what will be rendered.
When the Phoneword application is run on any platform, it displays a single screen that corresponds to a Page in
Xamarin.Forms. A Page represents a ViewGroup in Android, a View Controller in iOS, or a Page on the Universal
Windows Platform. The Phoneword application also instantiates a ContentPage object that represents the
MainPage class, whose XAML markup is shown in the following code example:
<?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="Phoneword.MainPage">
...
<StackLayout>
<Label Text="Enter a Phoneword:" />
<Entry x:Name="phoneNumberText" Text="1-855-XAMARIN" />
<Button x:Name="translateButon" Text="Translate" Clicked="OnTranslate" />
<Button x:Name="callButton" Text="Call" IsEnabled="false" Clicked="OnCall" />
</StackLayout>
</ContentPage>

The MainPage class uses a StackLayout control to automatically arrange controls on the screen regardless of the
screen size. Each child element is positioned one after the other, vertically in the order in which they are added. The
StackLayout control contains a Label control to display text on the page, an Entry control to accept textual user
input, and two Button controls used to execute code in response to touch events.
For more information about XAML in Xamarin.Forms, see Xamarin.Forms XAML Basics.
Responding to User Interaction
An object defined in XAML can fire an event that is handled in the code-behind file. The following code example
shows the OnTranslate method in the code-behind for the MainPage class, which is executed in response to the
Clicked event firing on the Translate button.

void OnTranslate(object sender, EventArgs e)


{
translatedNumber = Core.PhonewordTranslator.ToNumber (phoneNumberText.Text);
if (!string.IsNullOrWhiteSpace (translatedNumber)) {
callButton.IsEnabled = true;
callButton.Text = "Call " + translatedNumber;
} else {
callButton.IsEnabled = false;
callButton.Text = "Call";
}
}

The OnTranslate method translates the phoneword into its corresponding phone number, and in response, sets
properties on the call button. The code-behind file for a XAML class can access an object defined in XAML using
the name assigned to it with the x:Name attribute. The value assigned to this attribute has the same rules as C#
variables, in that it must begin with a letter or underscore and contain no embedded spaces.
The wiring of the translate button to the OnTranslate method occurs in the XAML markup for the MainPage class:

<Button x:Name="translateButon" Text="Translate" Clicked="OnTranslate" />

Additional Concepts Introduced in Phoneword


The Phoneword application for Xamarin.Forms has introduced several concepts not covered in this article. These
concepts include:
Enabling and disabling buttons. A Button can be toggled on or off by changing its IsEnabled property. For
example, the following code example disables the callButton :

callButton.IsEnabled = false;
Displaying an alert dialog. When the user presses the call Button the Phoneword application shows an
Alert Dialog with the option to place or cancel a call. The DisplayAlert method is used to create the dialog,
as shown in the following code example:

await this.DisplayAlert (
"Dial a Number",
"Would you like to call " + translatedNumber + "?",
"Yes",
"No");

Accessing native features via the DependencyService class. The Phoneword application uses the
DependencyService class to resolve the IDialer interface to platform -specific phone dialing
implementations, as shown in the following code example from the Phoneword project:

async void OnCall (object sender, EventArgs e)


{
...
var dialer = DependencyService.Get<IDialer> ();
...
}

For more information about the DependencyService class, see Accessing Native Features via the
DependencyService.
Placing a phone call with a URL. The Phoneword application uses OpenURL to launch the system phone app.
The URL consists of a tel: prefix followed by the phone number to be called, as shown in the following
code example from the iOS project:

return UIApplication.SharedApplication.OpenUrl (new NSUrl ("tel:" + number));

Tweaking the platform layout. The Device class enables developers to customize the application layout and
functionality on a per-platform basis, as shown in the following code example that uses different Padding
values on different platforms to correctly display each page:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" ... >


<ContentPage.Padding>
<OnPlatform x:TypeArguments="Thickness">
<On Platform="iOS" Value="20, 40, 20, 20" />
<On Platform="Android, UWP" Value="20" />
</OnPlatform>
</ContentPage.Padding>
...
</ContentPage>

For more information about platform tweaks, see Device Class.

Testing and Deployment


Visual Studio for Mac and Visual Studio both provide many options for testing and deploying an application.
Debugging applications is a common part of the application development lifecycle and helps to diagnose code
issues. For more information, see Set a Breakpoint, Step Through Code, and Output Information to the Log
Window.
Simulators are a good place to start deploying and testing an application, and feature useful functionality for
testing applications. However, users will not consume the final application in a simulator, so applications should be
tested on real devices early and often. For more information about iOS device provisioning, see Device
Provisioning. For more information about Android device provisioning, see Set Up Device for Development.

Summary
This article has examined the fundamentals of application development using Xamarin.Forms. Topics covered
included the anatomy of a Xamarin.Forms application, architecture and application fundamentals, and the user
interface.
In the next section of this guide the application will be extended to include multiple screens, to explore more
advanced Xamarin.Forms architecture and concepts.
Hello, Xamarin.Forms Multiscreen
7/25/2018 • 2 minutes to read • Edit Online

This guide expands the Phoneword application created in the Hello, Xamarin.Forms guide to navigate to a second
screen. Topics covered include page navigation and data binding to a collection.

Part 1: Quickstart
The first part of this guide demonstrates how to add a second screen to the Phoneword application to keep track of
the call history for the application.

Part 2: Deep Dive


The second part of this guide reviews what has been built, to develop an understanding of page navigation and
data binding in a Xamarin.Forms application.

Related Links
Introduction to Xamarin.Forms
Debugging in Visual Studio
Visual Studio for Mac Recipes - Debugging
Free Self-Guided Learning (video)
Getting Started with Xamarin (video)
Xamarin.Forms Multiscreen Quickstart
7/12/2018 • 6 minutes to read • Edit Online

This quickstart demonstrates how to extend the Phoneword application by adding a second screen to keep track of
the call history for the application. The final application is shown below:

Extend the Phoneword application as follows:


Visual Studio
Visual Studio for Mac
1. Launch Visual Studio. On the start page click Open Project..., and in the Open Project dialog select the
solution file for the Phoneword project:
2. In Solution Explorer, right click on the Phoneword project and select Add > New Item...:

3. In the Add New Item dialog, select Visual C# Items > Xamarin.Forms > Content Page, name the new
item CallHistoryPage, and click the Add button. This will add a page named CallHistoryPage to the
project:

4. In CallHistoryPage.xaml, remove all of the template code and replace it with the following code. This code
declaratively defines the user interface for the page:
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:local="clr-namespace:Phoneword;assembly=Phoneword"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Phoneword.CallHistoryPage"
Title="Call History">
<ContentPage.Padding>
<OnPlatform x:TypeArguments="Thickness">
<On Platform="iOS" Value="20, 40, 20, 20" />
<On Platform="Android, UWP" Value="20" />
</OnPlatform>
</ContentPage.Padding>
<StackLayout>
<ListView ItemsSource="{x:Static local:App.PhoneNumbers}" />
</StackLayout>
</ContentPage>

Save the changes to CallHistoryPage.xaml by pressing CTRL+S, and close the file.
5. In Solution Explorer, double-click the App.xaml.cs file in the shared Phoneword project to open it:

6. In App.xaml.cs, import the System.Collections.Generic namespace, add the declaration of the


PhoneNumbers property, initialize the property in the App constructor, and initialize the MainPage property
to be a NavigationPage . The PhoneNumbers collection will be used to store a list of each translated phone
number called by the application:
using System.Collections.Generic;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

[assembly: XamlCompilation(XamlCompilationOptions.Compile)]
namespace Phoneword
{
public partial class App : Application
{
public static IList<string> PhoneNumbers { get; set; }

public App()
{
InitializeComponent();
PhoneNumbers = new List<string>();
MainPage = new NavigationPage(new MainPage());
}
...
}
}

Save the changes to App.xaml.cs by pressing CTRL+S, and close the file.
7. In Solution Explorer, double-click the MainPage.xaml file in the shared Phoneword project to open it:

8. In MainPage.xaml, add a Button control at the end of the StackLayout control. The button will be used to
navigate to the call history page:

<StackLayout VerticalOptions="FillAndExpand"
HorizontalOptions="FillAndExpand"
Orientation="Vertical"
Spacing="15">
...
<Button x:Name="callButton" Text="Call" IsEnabled="false" Clicked="OnCall" />
<Button x:Name="callHistoryButton" Text="Call History" IsEnabled="false"
Clicked="OnCallHistory" />
</StackLayout>

Save the changes to MainPage.xaml by pressing CTRL+S, and close the file.
9. In Solution Explorer, double-click MainPage.xaml.cs to open it:

10. In MainPage.xaml.cs, add the OnCallHistory event handler method, and modify the OnCall event
handler method to add the translated phone number to the App.PhoneNumbers collection and enable the
callHistoryButton , provided that the dialer variable is not null :

using System;
using Xamarin.Forms;

namespace Phoneword
{
public partial class MainPage : ContentPage
{
...

async void OnCall(object sender, EventArgs e)


{
...
if (dialer != null) {
App.PhoneNumbers.Add (translatedNumber);
callHistoryButton.IsEnabled = true;
dialer.Dial (translatedNumber);
}
...
}

async void OnCallHistory(object sender, EventArgs e)


{
await Navigation.PushAsync (new CallHistoryPage ());
}
}
}

Save the changes to MainPage.xaml.cs by pressing CTRL+S, and close the file.
11. In Visual Studio, select the Build > Build Solution menu item (or press CTRL+SHIFT+B ). The application
will build and a success message will appear in the Visual Studio status bar:
If there are errors, repeat the previous steps and correct any mistakes until the application builds
successfully.
12. In the Visual Studio toolbar, press the Start button (the triangular button that resembles a Play button) to
launch the application:

13. In Solution Explorer, right click on the Phoneword.Droid project and select Set as StartUp Project.
14. In the Visual Studio toolbar, press the Start button (the triangular button that resembles a Play button) to
launch the application inside an Android emulator.
15. If you have an iOS device and meet the Mac system requirements for Xamarin.Forms development, use a
similar technique to deploy the app to the iOS device. Alternatively, deploy the app to the iOS remote
simulator.
Note: phone calls are not supported on all the simulators.
Congratulations on completing a multiscreen Xamarin.Forms application. The next topic in this guide reviews the
steps that were taken in this walkthrough to develop an understanding of page navigation and data binding using
Xamarin.Forms.
Related Links
Phoneword (sample)
PhonewordMultiscreen (sample)
Xamarin.Forms Multiscreen Deep Dive
7/12/2018 • 3 minutes to read • Edit Online

In the Xamarin.Forms Multiscreen Quickstart, the Phoneword application was extended to include a second screen
that keeps track of the call history for the application. This article reviews what has been built, to develop an
understanding of page navigation and data binding in a Xamarin.Forms application.

Navigation
Xamarin.Forms provides a built-in navigation model that manages the navigation and user-experience of a stack of
pages. This model implements a last-in, first-out (LIFO ) stack of Page objects. To move from one page to another
an application will push a new page onto this stack. To return back to the previous page the application will pop
the current page from the stack.
Xamarin.Forms has a NavigationPage class that manages the stack of Page objects. The NavigationPage class will
also add a navigation bar to the top of the page that displays a title and a platform-appropriate Back button that
will return to the previous page. The following code example shows how to wrap a NavigationPage around the
first page in an application:

public App ()
{
...
MainPage = new NavigationPage (new MainPage ());
}

All ContentPage instances have a Navigation property that exposes methods to modify the page stack. These
methods should only be invoked if the application includes a NavigationPage . To navigate to the CallHistoryPage ,
it is necessary to invoke the PushAsync method as demonstrated in the code example below:

async void OnCallHistory(object sender, EventArgs e)


{
await Navigation.PushAsync (new CallHistoryPage ());
}

This causes the new CallHistoryPage object to be pushed onto the Navigation stack. To programmatically return
back to the original page, the CallHistoryPage object must invoke the PopAsync method, as demonstrated in the
code example below:

await Navigation.PopAsync();

However, in the Phoneword application this code isn't required as the NavigationPage class adds a navigation bar
to the top of the page that includes a platform appropriate Back button that will return to the previous page.

Data Binding
Data binding is used to simplify how a Xamarin.Forms application displays and interacts with its data. It
establishes a connection between the user interface and the underlying application. The BindableObject class
contains much of the infrastructure to support data binding.
Data binding defines the relationship between two objects. The source object will provide data. The target object
will consume (and often display) the data from the source object. In the Phoneword application, the binding target
is the ListView control that displays phone numbers, while the PhoneNumbers collection is the binding source.
The PhoneNumbers collection is declared and initialized in the App class, as shown in the following code example:

public partial class App : Application


{
public static List<string> PhoneNumbers { get; set; }

public App ()
{
PhoneNumbers = new List<string>();
...
}
...
}

The ListView instance is declared and initialized in the CallHistoryPage class, as shown in the following code
example:

<?xml version="1.0" encoding="UTF-8"?>


<ContentPage ...
xmlns:local="clr-namespace:Phoneword;assembly=Phoneword"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
...>
...
<ContentPage.Content>
...
<ListView ItemsSource="{x:Static local:App.PhoneNumbers}" />
...
</ContentPage.Content>
</ContentPage>

In this example, the ListView control will display the IEnumerable collection of data that the ItemsSource
property binds to. The collection of data can be objects of any type, but by default, ListView will use the ToString
method of each item to display that item. The x:Static markup extension is used to indicate that the ItemsSource
property will be bound to the static PhoneNumbers property of the App class, which can be located in the local
namespace.
For more information about data binding, see Data Binding Basics. For more information about XAML markup
extensions, see XAML Markup Extensions.

Additional Concepts Introduced in Phoneword


The ListView is responsible for displaying a collection of items on the screen. Each item in the ListView is
contained in a single cell. For more information about using the ListView control, see ListView.

Summary
This article has introduced page navigation and data binding in a Xamarin.Forms application, and demonstrated
their use in a multi-screen cross-platform application.
An Introduction to Xamarin.Forms
7/12/2018 • 21 minutes to read • Edit Online

Xamarin.Forms is a cross-platform natively backed UI toolkit abstraction that allows developers to easily create
user interfaces that can be shared across Android, iOS, Windows, and the Universal Windows Platform. The user
interfaces are rendered using the native controls of the target platform, allowing Xamarin.Forms applications to
retain the appropriate look and feel for each platform. This article provides an introduction to Xamarin.Forms
and how to get started writing applications with it.

Overview
Xamarin.Forms is a framework that allows developers to rapidly create cross platform user interfaces. It provides
its own abstraction for the user interface that will be rendered using native controls on iOS, Android, or the
Universal Windows Platform (UWP ). This means that applications can share a large portion of their user
interface code and still retain the native look and feel of the target platform.
Xamarin.Forms allows for rapid prototyping of applications that can evolve over time to complex applications.
Because Xamarin.Forms applications are native applications, they don't have the limitations of other toolkits such
as browser sandboxing, limited APIs, or poor performance. Applications written using Xamarin.Forms are able to
utilize any of the API’s or features of the underlying platform, such as (but not limited to) CoreMotion, PassKit,
and StoreKit on iOS; NFC and Google Play Services on Android; and Tiles on Windows. In addition, it's possible
to create applications that will have parts of their user interface created with Xamarin.Forms while other parts
are created using the native UI toolkit.
Xamarin.Forms applications are architected in the same way as traditional cross-platform applications. The most
common approach is to use Portable Libraries or Shared Projects to house the shared code, and create platform
specific applications that will consume the shared code.
There are two techniques to create user interfaces in Xamarin.Forms. The first technique is to create UIs entirely
with C# source code. The second technique is to use Extensible Application Markup Language (XAML ), a
declarative markup language that is used to describe user interfaces. For more information about XAML, see
XAML Basics.
This article discusses the fundamentals of the Xamarin.Forms framework, and covers the following topics:
Examining a Xamarin.Forms application.
How Xamarin.Forms pages and controls are used.
How to use display a list of data.
How to set up data binding.
How to navigate between pages.
Next steps.
Examining a Xamarin.Forms Application
In Visual Studio for Mac and Visual Studio, the default Xamarin.Forms app template creates the simplest
Xamarin.Forms solution possible, which displays text to the user. If you run the application, it should appear
similar to the following screenshots:
Each screen in the screenshots corresponds to a Page in Xamarin.Forms. A Page represents an Activity in
Android, a View Controller in iOS, or a Page in the Windows Universal Platform (UWP ). The sample in the
screenshots above instantiates a ContentPage object and uses that to display a Label .
To maximize the reuse of the startup code, Xamarin.Forms applications have a single class named App that is
responsible for instantiating the first Page that will be displayed. An example of the App class can be seen in the
following code:

public class App : Application


{
public App ()
{
MainPage = new ContentPage {
Content = new Label
{
Text = "Hello, Forms !",
VerticalOptions = LayoutOptions.CenterAndExpand,
HorizontalOptions = LayoutOptions.CenterAndExpand,
}
};
}
}

This code instantiates a new ContentPage object that will display a single Label centered both vertically and
horizontally on the page.
Launching the Initial Xamarin.Forms Page on Each Platform
To use this Page inside an application, each platform application must initialize the Xamarin.Forms framework
and provide an instance of the ContentPage as it is starting up. This initialization step varies from platform to
platform and is discussed in the following sections.
iOS
To launch the initial Xamarin.Forms page in iOS, the platform project includes the AppDelegate class that inherits
from the Xamarin.Forms.Platform.iOS.FormsApplicationDelegate class, as demonstrated in the following code
example:
[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.Init ();
LoadApplication (new App ());
return base.FinishedLaunching (app, options);
}
}

The FinishedLoading override initializes the Xamarin.Forms framework by calling the Init method. This causes
the iOS -specific implementation of Xamarin.Forms to be loaded in the application before the root view controller
is set by the call to the LoadApplication method.
Android
To launch the initial Xamarin.Forms page in Android, the platform project includes code that creates an Activity
with the MainLauncher attribute, with the activity inherting from the FormsAppCompatActivity class, as
demonstrated in the following code example:

namespace HelloXamarinFormsWorld.Android
{
[Activity(Label = "HelloXamarinFormsWorld", Theme = "@style/MainTheme", MainLauncher = true,
ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : FormsAppCompatActivity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication (new App ());
}
}
}

The OnCreate override initializes the Xamarin.Forms framework by calling the Init method. This causes the
Android-specific implementation of Xamarin.Forms to be loaded in the application before the Xamarin.Forms
application is loaded.
Universal Windows Platform
In Universal Windows Platform (UWP ) applications, the Init method that initializes the Xamarin.Forms
framework is invoked from the App class:

Xamarin.Forms.Forms.Init (e);

if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
...
}

This causes the UWP -specific implementation of Xamarin.Forms to be loaded in the application. The initial
Xamarin.Forms page is launched by the MainPage class, as demonstrated in the following code example:
public partial class MainPage
{