Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 33

Chapter 1 Introduction

1 Introduction

Xamarin is an open-source platform for building modern and Performant


applications for iOS, Android, and Windows with .NET. Xamarin is an abstraction layer
that manages communication of shared code with underlying platform code. Xamarin runs
in a managed environment that provides conveniences such as memory allocation and
garbage collection.

Xamarin enables developers to share an average of 90% of their application across


platforms. This pattern allows developers to write all of their business logic in a single
language (or reuse existing application code) but achieve native performance, look, and feel
on each platform.

Xamarin applications can be written on PC or Mac and compile into native


application packages, such as an .apk file on Android, or an .ipa file on iOS.
 
Note
Compiling and deploying applications for iOS currently requires a MacOS machine. For
more information about development requirements, see system requirements.

1.1 Origins of Xamarin


Xamarin is a Microsoft-owned San Francisco-based software company founded in
May 2011 by the engineers that created Mono, Xamarin.Android (formerly Mono for
Android) and Xamarin.iOS (formerly MonoTouch), which are cross-platform
implementations of the Common Language Infrastructure (CLI) and Common Language
Specifications (often called Microsoft .NET).

May
2011 Xamarin as a company is incorporated with the idea of building commercial
.NET offerings for iOS and Android. In July, Novell gives Xamarin the rights to
use MonoTouch and Mono for Android.

1
Chapter 1 Introduction

Feb
On February 24, 2016 Xamarin and Microsoft announced that Microsoft signed
2016
a definitive agreement to acquire Xamarin. Terms of the deal were not disclosed,
though the Wall Street Journal reported the price at between $400 million and
$500 million.
Microsoft acquires Xamarin and releases Xamarin as part of Visual Studio suite of tools.

2 Apr
2019 The Xamarin workload in Visual Studio 2019 is now 3.28 xs smaller than our
Visual Studio 2017 version 15.5 release, going from just over 23GB to 7GB in
Visual Studio 2019, enabling you a faster installation experience and a lower
disk impact.

1.2 What is Cross-Platform


 For mobile, tablet, and desktop applications, Xamarin provides a cross-platform
development solution.
 Building the mobile apps can be easy as opening up the IDE, writing and testing an
app and submitting to an app store. It involves a process that involves the up-front
design, Usability testing, QA testing on thousands of devices, a full beta lifecycle, and
then deployment in several different ways.
 When we think about how to build Android and iOS application, many people
believe that the native language, objective-C, Swift, Java, and Kotlin are the only
choice.
 Xamarin allows us to develop in C# with a class library and runtime which works
across all many platforms including ios, Windows, and Android.

1.3 Comparison to Other Development Platforms


1.3.1 Apple or Android Native
Native applications offer the least friction in adopting new features. They tend to
have user experiences more in tune with the given platform since the applications are built

2
Chapter 1 Introduction

using controls from the platforms vendors themselves (Apple or Google) and often follow
design guidelines set out by these vendors.

One big advantage native applications have is they can adopt brand new
technologies Apple and Google create in beta immediately if desired, without having to wait
for any third-party integration. The main disadvantage to building native applications is the
lack of code reuse across platforms, which can make development expensive if targeting
iOS and Android
.

1.3.2 React Native


React Native allows native applications to be built using JavaScript. The actual
controls the application uses are native platform controls, so the end user gets the feel of a
native app. For apps that require customization beyond what React Native's abstraction
provides, native development could still be needed. In cases where the amount of
customization required is substantial, the benefit of working within React Native's
abstraction layer lessens to the point where in some cases developing the app natively
would be more beneficial.

1.3.3 Flutter
Flutter is an open-source framework by Google. Take a note to the point that Flutter
is not a language, but it is an app development framework for crafting UI. Flutter was
specially developed for Google Fuchsia, later they made it an open-source for various
platforms.
Flutter offers readymade widgets, command-line tools, APIs and almost every tool
need to build an application. By now, Flutter has expanded Flutter SDK to embedded
devices, desktop, and web.

3
Chapter 1 Introduction

1.1 Development platform Similar to Xamarin

4
Chapter 2 Architecture

2 Architecture

A key tenet of building cross-platform apps is to create an architecture that lends


itself to a maximization of code sharing across platforms. Adhering to the following Object
Oriented Programming principles helps build a well-architected application:

Architecture is described in the Chapter in three places:


 Xamarin.Android Architecture
 Xamarin.iOS Architecture
 Xamarin.Form

In general, C# code and .NET APIs sit on top of Mono runtime, which in turn sits on
top of the OS kernel. Architecture allows for managed code to invoke native APIs via
bindings. In Android, Managed Callable Wrappers (MCW) is used when managed code
needs to invoke Android code; Android Callable Wrappers (ACW) is used when Android
runtime needs to invoke managed code. There's also the Java Native Interface (JNI) for one-
off use of unbound Java types and members.

How Xamarin works

2.1 Architecture of Xamarin

The diagram shows the overall architecture of a cross-platform Xamarin application.


Xamarin allows you to create native UI on each platform and write business logic in C# that

5
Chapter 2 Architecture

is shared across platforms. In most cases, 80% of application code is sharable using
Xamarin.

Xamarin is built on top of Mono, an open-source version of the .NET Framework


based on the .NET ECMA standards. Mono has existed for almost as long as the .NET
Framework itself, and runs on most platforms including Linux, UNIX, FreeBSD, and
macOS. The Mono execution environment automatically handles tasks such as memory
allocation, garbage collection and interoperability with underlying platforms.

For more information about platform-specific architecture, see Xamarin.Android 


and Xamarin.iOS.

Added features

Xamarin combines the abilities of native platforms and adds a number of features,
including:

1. Complete binding for the underlying SDKs – Xamarin contains bindings for
nearly the entire underlying platform SDKs in both iOS and Android. Additionally,
these bindings are strongly-typed, which means that they’re easy to navigate and use,
and provide robust compile-time type checking and during development. Strongly-
typed bindings lead to fewer runtime errors and higher-quality applications.

2. Objective-C, Java, C, and C++ Interop – Xamarin provides facilities for directly
invoking Objective-C, Java, C, and C++ libraries, giving you the power to use a wide
array of third party code. This functionality lets you use existing iOS and Android
libraries written in Objective-C, Java, or C/C++. Additionally, Xamarin offers binding
projects that allow you to bind native Objective-C and Java libraries using a
declarative syntax.

3. Modern language constructs – Xamarin applications are written in C#, a modern


language that includes significant improvements over Objective-C and Java such as
dynamic language features, functional constructs such as lambdas, LINQ, parallel
programming, generics, and more.

6
Chapter 2 Architecture

4. Robust Base Class Library (BCL) – Xamarin applications use the .NET BCL, a
large collection of classes that have comprehensive and streamlined features such as
powerful XML, Database, Serialization, IO, String, and Networking support, and
more. Existing C# code can be compiled for use in an app, which provides access to
thousands of libraries that add functionality beyond the BCL.

5. Modern Integrated Development Environment (IDE) – Xamarin uses Visual


Studio, a modern IDE that includes features such as code auto completion, a
sophisticated project and solution management system, a comprehensive project
template library, integrated source control, and more.

6. Mobile cross-platform support – Xamarin offers sophisticated cross-platform


support for the three major platforms of iOS, Android, and Windows. Applications
can be written to share up to 90% of their code, and Xamarin. Essentials offer a
unified API to access common resources across all three platforms. Shared code can
significantly reduce both development costs and time to market for mobile
developers.
1.1 Xamarin. Android

2.2 Xamarin.Android applications compile

Xamarin.Android applications compile from C# into Intermediate Language


(IL) which is then Just-in-Time (JIT) compiled to a native assembly when the application
launches. Xamarin. Android applications run within the Mono execution environment, side
by side with the Android Runtime (ART) virtual machine. Xamarin provides .NET bindings
to the Android.* and Java.* namespaces. The Mono execution environment calls into these

7
Chapter 2 Architecture

namespaces via Managed Callable Wrappers (MCW) and provides Android Callable


Wrappers (ACW) to the ART, allowing both environments to invoke code in each other.

2.2 Xamarin. IOS

2.3 Xamarin. iOS architecture

Xamarin.iOS applications are fully Ahead-of-Time (AOT) compiled from C# into


native ARM assembly code. Xamarin uses Selectors to expose Objective-C to managed C#
and Registrars to expose managed C# code to Objective-C. Selectors and Registrars
collectively are called "bindings" and allow Objective-C and C# to communicate.

Xamarin.Essentials

Xamarin.Essentials is a library that provides cross-platform APIs for native device


features. Like Xamarin itself, Xamarin.Essentials is an abstraction that simplifies the
process of accessing native functionality. Some examples of functionality provided by
Xamarin.Essentials include:

 Device info
 File system
 Accelerometer
 Phone dialer
 Text-to-speech
 Screen lock

8
Chapter 2 Architecture

2.3 Xamarin.Forms

Xamarin.Forms is an open-source UI framework. Xamarin.Forms allows developers


to build iOS, Android and Windows applications from a single shared codebase.
Xamarin.Forms allows developers to create user interfaces in XAML with code-behind in
C#. These user interfaces are rendered as performant native controls on each platform.
Some examples of features provided by Xamarin.Forms include:

 XAML user-interface language


 Data binding
 Gestures
 Effects
 Styling

9
Chapter 3 Environment Setup and Installation

3 Environment Setup and Installation

Xamarin products rely upon the platform SDKs from Apple and Google to target
iOS or Android, so our system requirements match theirs. This page outlines system
compatibility for the Xamarin platform and recommended development environment and
SDK versions.

Take a look at the installation instructions for more information on obtaining the


software and required SDKs.

3.1. Development environments

This table shows which platforms can be built with different development tool & operating
system combinations:

macOS Windows
Development Visual Studio for Visual Studio
Environment Mac
Xamarin.iOS Yes Yes (with Mac computer)
Xamarin.Android Yes Yes
Xamarin.Forms iOS & Android Android, Windows/UWP (iOS with
Mac computer)
Xamarin.mac Yes Open project & compile only

 Note
To develop for iOS on Windows computers there must be a Mac computer accessible on the
network, for remote compilation and debugging. This also works if you have Visual Studio running
inside a Windows VM on a Mac computer.

3.2. MacOS requirements

Using a Mac computer for Xamarin development requires the following software/SDK
versions. Check your operating system version and follow the instructions for the Xamarin installer.

Recommended Notes
Operating macOS Mojave Xcode 10 requires macOS High Sierra (10.13) or

10
Chapter 3 Environment Setup and Installation

System (10.14) newer.


Xamarin.iOS iOS 12 SDK The iOS 12 SDK ships with Xcode 10.
Xamarin.Android Android 6.0 / API You can still target older Android versions while
level 23 using the latest SDK, or you can build against
older versions of the SDK if required.
Xamarin.Forms  Xamarin.Forms apps built on macOS can
include iOS, Android, and macOS projects,
subject to the SDK requirements above.
 Xamarin.Forms projects for
Windows/UWP cannot be built on macOS.
Xamarin.Mac macOS Mojave The macOS Mojave (10.14) SDK ships with
(10.14) SDK Xcode 10 and is required to build apps that use
the newest macOS APIs.

 Note
Xcode can be installed (and updated) on developer.apple.com or via the Mac App Store.

3.2.1. Testing & debugging on macOS

Xamarin mobile applications can be deployed to physical devices via USB for
testing and debugging (Apple Watch apps are deployed first to the paired iPhone).
Xamarin.Mac apps can be tested directly on the development computer.

Testing Notes
Xamarin.iOS  The easiest way to get started is using the iPhone, iPad, Apple
Watch, and Apple TV simulators that are included with Xcode.
 To use a device for testing, follow these instructions.
Xamarin.Androi Follow these instructions to configure your device, or use an emulator:
d  The Xamarin installer includes the Google Emulator Manager
which lets you configure Google Android emulators for testing.
Xamarin.Forms Xamarin.Forms apps for iOS and Android can be deployed to the
relevant platforms as described above.
Xamarin.Mac Xamarin.Mac apps can be tested directly on the development computer.

11
Chapter 3 Environment Setup and Installation

 Warning
Xamarin.Mac 4.8 only supports macOS 10.9 (Mavericks) or higher. Previous versions of
Xamarin.Mac supported macOS 10.7 or higher, but these older macOS versions lack sufficient TLS
infrastructure to support TLS 1.2. To target macOS 10.7 or macOS 10.8, use Xamarin.Mac 4.6 or
earlier.

3.3. Windows requirements

Using a Windows computer for Xamarin development requires the following software/SDK
versions. Check your operating system version (and confirm that you are not using
an Express version of Visual Studio - if so, consider updating to a Community edition). The Visual
Studio 2019 and Visual Studio 2017 installer includes an option to install Xamarin automatically
(the Mobile development with .NET workload).

Recommended Notes
Operating Windows 10 The minimum operating system version is
System Windows 7. Xamarin.Forms UWP support
requires Windows 10.
Xamarin.iOS iOS 10 SDK To build iOS projects on Windows requires:
(installed on a  Visual Studio 2017 (Visual Studio 2019 is
Mac) recommended), and
 A Mac computer, network-accessible from
the Windows computer, that conforms to the
minimum requirements for running Xamarin
on macOS.
Xamarin.Android Android 6.0 / API You can still target older Android versions while
level 23 using the latest SDK, or you can build against
older versions of the SDK if required.
Xamarin.Forms  Xamarin.Forms apps for iOS and Android
can be deployed to the relevant platforms as
described above.
 Using Visual Studio also means you can
test apps for the Universal Windows
Platform (on Windows 10) directly on the
development computer.
Xamarin.Mac Xamarin.Mac projects (macOS desktop apps) can

12
Chapter 3 Environment Setup and Installation

be opened in Visual Studio and compiled to check


for errors, but Mac applications cannot currently
be built for distribution in Visual Studio.

 Note
 Xamarin for Visual Studio supports Visual Studio 2019 or Visual Studio 2017 (Community,
Professional, and Enterprise).
 To use the latest Android and iOS SDKs requires the latest version of Visual Studio. For
specific version requirements, refer to the Xamarin.Android release notes and Xamarin.iOS
release notes.
 To develop Xamarin.Forms apps for the Universal Windows Platform (UWP) requires
Windows 10 with Visual Studio 2017. Visual Studio 2019 is recommended.

3.3.1. Testing & debugging on Windows

Xamarin mobile applications can be deployed to physical devices via USB or wirelessly for
testing and debugging (iOS devices must be connected to the Mac computer, not the computer
running Visual Studio).

Testing Notes
Xamarin.iOS  The easiest way to get started is using the iPhone, iPad, Apple
Watch, and Apple TV simulators that are included with Xcode.
The simulators can be accessed on the connected Mac while
debugging with Visual Studio.
 To use a device for testing, follow these
instructions (performing most steps on the connected Mac
computer).
Xamarin.Androi Follow these instructions to configure your device, or use an emulator:
d  The Xamarin installer includes the Google Emulator
Manager which lets you configure Google Android emulators for
testing.
Xamarin.Forms
Xamarin.Forms apps can be deployed to the relevant devices and
emulators as described above. The iOS app can only be tested via the
connected Mac hardware; and the Windows tablet/desktop apps for
UWP can be tested directly on the development computer.

13
Chapter 3 Environment Setup and Installation

3.4. Installing Xamarin


How to set up Visual Studio and Xamarin to start building mobile apps with .NET.

3.1.1 Adding Xamarin to Visual Studio 2019


If Visual Studio 2019 is already installed, add Xamarin by re-running the Visual
Studio 2019 installer to modify workloads (see Modify Visual Studio for details). Next,
follow the steps listed above to install Xamarin.

3.2 Installation
Xamarin can be installed as part of a new Visual Studio 2019 installation, with the
following steps:

1. Download Visual Studio 2019 Community, Visual Studio Professional, or Visual


Studio Enterprise from the Visual Studio page (download links are provided at the
bottom).

2. Double-click the downloaded package to start installation.

3. Select the Mobile development with .NET workload from the installation screen:

3.1 Install Xamarin in Visual Studio

14
Chapter 3 Environment Setup and Installation

4. When you are ready to begin Visual Studio 2019 installation, click the Install button
in the lower right-hand corner:

Use the progress bars to monitor the installation:

5. When Visual Studio 2019 installation has completed, click the Launch button to


start Visual Studio:

In Visual Studio 2019, verify that Xamarin is installed by clicking the Help menu. If


Xamarin is installed, you should see a Xamarin menu item as shown in this screenshot:

15
Chapter 3 Environment Setup and Installation

You can also click Help > about Microsoft Visual Studio and scroll through the list of
installed products to see if Xamarin is installed:

3.2 Check Xamarin installed Package

3.3

16
Chapter 3 Environment Setup and Installation

Next steps

Installing Xamarin in Visual Studio 2019 allows you to start writing code for your apps, but
does require additional setup for building and deploying your apps to simulator, emulator,
and device. Visit the following guides to complete your installation and start building cross
platform apps.

3.5. Installing Xamarin Preview on Windows

The Preview version of Visual Studio may include corresponding Preview versions of
Xamarin functionality, including:

 Xamarin.Forms
 Xamarin.iOS
 Xamarin.Android
 Xamarin Profiler
 Xamarin Inspector
 Xamarin Remote iOS Simulator

The Preview Installer screenshot below shows both Preview and Release options (notice
the grey version numbers: version 15.0 is release and version 15.1 is a Preview):

17
Chapter 4 Model View ViewModel

4 Model-View-ViewModel

MVVM stands for Model-View-ViewModel. MVVM stands as a separation of code


into the domain-relevant data (the model) and the representation of the data (View) and,
finally, the logic (called the business logic) of our program (ViewModel). The responsibility
of ViewModel is visibility.

 Encapsulation – Ensuring that classes and even architectural layers only expose a
minimal API that performs their required functions, and hides the implementation
details. At a class level, this means that objects behave as ‘black boxes’ and that
consuming code does not need to know how they accomplish their tasks. At an
architectural level, it means implementing patterns like Façade that encourage a
simplified API that orchestrates more complex interactions on behalf of the code in
more abstract layers. This means that the UI code (for example) should only be
responsible for displaying screens and accepting user-input; and never interacting with
the database directly. Similarly the data-access code should only read and write to the
database, but never interact directly with buttons or labels.

 Separation of Responsibilities – Ensure that each component (both at architectural


and class level) has a clear and well-defined purpose. Each component should perform
only its defined tasks and expose that functionality via an API that is accessible to the
other classes that need to use it.

 Polymorphism – Programming to an interface (or abstract class) that supports


multiple implementations means that core code can be written and shared across
platforms, while still interacting with platform-specific features.

The natural outcome is an application modeled after real world or abstract entities
with separate logical layers. Separating code into layers make applications easier to
understand, test and maintain. It is recommended that the code in each layer be physically
separate (either in directories or even separate projects for very large applications) as well
as logically separate (using namespaces).

18
Chapter 4 Model View ViewModel

5 Typical Application Layers

Throughout this document and the case studies we refer to the following six
application layers:

 Data Layer – Non-volatile data persistence, likely to be a Slate database but could
be implemented with XML files or any other suitable mechanism.
 Data Access Layer – Wrapper around the Data Layer that provides Create, Read,
Update, Delete (CRUD) access to the data without exposing implementation details to
the caller. For example, the DAL may contain SQL statements to query or update the
data but the referencing code would not need to know this.

 Business Layer – (sometimes called the Business Logic Layer or BLL) contains
business entity definitions (the Model) and business logic. Candidate for Business
Façade pattern.

 Service Access Layer – Used to access services in the cloud: from complex web
services (REST, JSON, WCF) to simple retrieval of data and images from remote
servers. Encapsulates the networking behavior and provides a simple API to be
consumed by the Application and UI layers.

 Application Layer – Code that’s typically platform specific (not generally shared
across platforms) or code that is specific to the application (not generally reusable). A
good test of whether to place code in the Application Layer versus the UI Layer is (a)
to determine whether the class has any actual display controls or (b) whether it could
be shared between multiple screens or devices (eg. iPhone and iPad).

 User Interface (UI) Layer – The user-facing layer contains screens, widgets and
the controllers that manage them.

An application may not necessarily contain all layers – for example the Service
Access Layer would not exist in an application that does not access network resources. A
very simple application might merge the Data Layer and Data Access Layer because the
operations are extremely basic.

19
Chapter 4 Model View ViewModel

6 Common Mobile Software Patterns

Patterns are an established way to capture recurring solutions to common problems.


Model, View, ViewModel (MVVM) – The Model-View-ViewModel pattern is popular
with frameworks that support data-binding, such as Xamarin.Forms. It was popularized by
XAML-enabled SDKs like Windows Presentation Foundation (WPF) and Silverlight; where
the ViewModel acts as a go-between between the data (Model) and user interface (View)
via data binding and commands.

 Model, View, Controller (MVC) – A common and often misunderstood pattern,


MVC is most often used when building User Interfaces and provides for a separation
between the actual definition of a UI Screen (View), the engine behind it that handles
interaction (Controller), and the data that populates it (Model). The model is actually a
completely optional piece and therefore, the core of understanding this pattern lies in
the View and Controller. MVC is a popular approach for iOS applications.

The MVVM pattern

There are three core components in the MVVM pattern: the model, the view, and the
view model. Each serves a distinct purpose. Figure shows the relationships between the
three components.

4.1 MVVM Designing Pattern

In addition to understanding the responsibilities of each component, it's also


important to understand how they interact with each other. At a high level, the view "knows
about" the view model, and the view model "knows about" the model, but the model is

20
Chapter 4 Model View ViewModel

unaware of the view model, and the view model is unaware of the view. Therefore, the view
model isolates the view from the model, and allows the model to evolve independently of
the view.

The benefits of using the MVVM pattern are as follows:


 If there's an existing model implementation that encapsulates existing business logic,
it can be difficult or risky to change it. In this scenario, the view model acts as an
adapter for the model classes and enables you to avoid making any major changes to
the model code.

 Developers can create unit tests for the view model and the model, without using the
view. The unit tests for the view model can exercise exactly the same functionality
as used by the view.

 The app UI can be redesigned without touching the code, provided that the view is
implemented entirely in XAML. Therefore, a new version of the view should work
with the existing view model.

 Designers and developers can work independently and concurrently on their


components during the development process. Designers can focus on the view,
while developers can work on the view model and model components.

The key to using MVVM effectively lies in understanding how to factor app code
into the correct classes, and in understanding how the classes interact. The following
sections discuss the responsibilities of each of the classes in the MVVM pattern.

 View
The view is responsible for defining the structure, layout, and appearance of what
the user sees on screen. Ideally, each view is defined in XAML, with a limited code-behind
that does not contain business logic. In some cases, the code-behind might contain UI logic
that implements visual behavior that is difficult to express in XAML, such as animations.

In a Xamarin.Forms application, a view is typically a Page-derived or Content View-


derived class. However, views can also be represented by a data template, which specifies

21
Chapter 4 Model View ViewModel

the UI elements to be used to visually represent an object when it's displayed. A data
template as a view does not have any code-behind, and is designed to bind to a specific
view model type.

Tip: Avoid enabling and disabling UI elements in the code-behind.


Ensure that view models are responsible for defining logical state changes that affect
some aspects of the view's display, such as whether a command is available, or an indication
that an operation is pending. Therefore, enable and disable UI elements by binding to view
model properties, rather than enabling and disabling them in code-behind.

There are several options for executing code on the view model in response to
interactions on the view, such as a button click or item selection. If a control supports
commands, the control's Command property can be data-bound to a Command property on
the view model. When the control's command is invoked, the code in the view model will
be executed. In addition to commands, behaviors can be attached to an object in the view
and can listen for either a command to be invoked or event to be raised. In response, the
behavior can then invoke an ICommand on the view model or a method on the view model.

 ViewModel

The view model implements properties and commands to which the view can data
bind to, and notifies the view of any state changes through change notification events. The
properties and commands that the view model provides define the functionality to be
offered by the UI, but the view determines how that functionality is to be displayed.

Tip: Keep the UI responsive with asynchronous operations.

Mobile apps should keep the UI thread unblocked to improve the user's perception
of performance. Therefore, in the view model, use asynchronous methods for I/O operations
and raise events to asynchronously notify views of property changes.

22
Chapter 4 Model View ViewModel

The view model is also responsible for coordinating the view's interactions with any
model classes that are required. There's typically a one-to-many relationship between the
view model and the model classes. The view model might choose to expose model classes
directly to the view so that controls in the view can data bind directly to them. In this case,
the model classes will need to be designed to support data binding and change notification
events.

Each view model provides data from a model in a form that the view can easily
consume. To accomplish this, the view model sometimes performs data conversion. Placing
this data conversion in the view model is a good idea because it provides properties that the
view can bind to. For example, the view model might combine the values of two properties
to make it easier for display by the view.

Tip: Centralize data conversions in a conversion layer.

It's also possible to use converters as a separate data conversion layer that sits
between the view model and the view. This can be necessary, for example, when data
requires special formatting that the view model doesn't provide.

In order for the view model to participate in two-way data binding with the view, its
properties must raise the Property Changed event. View models satisfy this requirement by
implementing the NotifyPropertyChanged interface, and raising the PropertyChanged event
when a property is changed.

For collections, the view-friendly ObservableCollection is provided. This collection


implements collection changed notification, relieving the developer from having to
implement the INotifyCollectionChanged interface on collections.

 Modal

Model classes are non-visual classes that encapsulate the app's data. Therefore, the
model can be thought of as representing the app's domain model, which usually includes a
data model along with business and validation logic. Examples of model objects include

23
Chapter 4 Model View ViewModel

data transfer objects (DTOs), Plain Old CLR Objects (POCOs), and generated entity and
proxy objects.

Model classes are typically used in conjunction with services or repositories that
encapsulate data access and caching.

 Connecting view models to views

View models can be connected to views by using the data-binding capabilities of


Xamarin.Forms. There are many approaches that can be used to construct views and view
models and associate them at runtime. These approaches fall into two categories, known as
view first composition, and view model first composition. Choosing between view first
composition and view model first composition is an issue of preference and complexity.
However, all approaches share the same aim, which is for the view to have a view model
assigned to its Binding Context property.

With view first composition the app is conceptually composed of views that connect
to the view models they depend on. The primary benefit of this approach is that it makes it
easy to construct loosely coupled, unit testable apps because the view models have no
dependence on the views themselves. It's also easy to understand the structure of the app by
following its visual structure, rather than having to track code execution to understand how
classes are created and associated. In addition, view first construction aligns with the
Xamarin.Forms navigation system that's responsible for constructing pages when navigation
occurs, which makes a view model first composition complex and misaligned with the
platform

With view model first composition the app is conceptually composed of view
models, with a service being responsible for locating the view for a view model. View
model first composition feels more natural to some developers, since the view creation can
be abstracted away, allowing them to focus on the logical non-UI structure of the app. In
addition, it allows view models to be created by other view models. However, this approach
is often complex and it can become difficult to understand how the various parts of the app
are created and associated.

Tip: Keep view models and views independent.

24
Chapter 4 Model View ViewModel

The binding of views to a property in a data source should be the view's principal
dependency on its corresponding view model. Specifically, don't reference view types, such
as Button and ListView, from view models. By following the principles outlined here, view
models can be tested in isolation, therefore reducing the likelihood of software defects by

<ContentPage ... xmlns:local="clr-namespace:eShop">


<ContentPage.BindingContext>

<local:LoginViewModel />

</ContentPage.BindingContext>
</ContentPage>

limiting scope.

Example for MVVM Pattern

Creating a view model declaratively

The simplest approach is for the view to declaratively instantiate its corresponding
view model in XAML. When the view is constructed, the corresponding view model object
will also be constructed. This approach is demonstrated in the following code example:

When the Content Page is created, an instance of the Login ViewModel is


automatically constructed and set as the view's Binding Context. This declarative
construction and assignment of the view model by the view has the advantage that it's
simple, but has the disadvantage that it requires a default (parameter-less) constructor in the
view model.

Creating a view model programmatically

A view can have code in the code-behind file that results in the view model being
assigned to its Binding Context property. This is often accomplished in the view's
constructor, as shown in the following code example:

25
Chapter 4 Model View ViewModel

public LoginView()
{
InitializeComponent();
BindingContext = new LoginViewModel(navigationService);
}

The programmatic construction and assignment of the view model within the view's code-
behind has the advantage that it's simple. However, the main disadvantage of this approach
is that the view needs to provide the view model with any required dependencies. Using a
dependency injection container can help to maintain loose coupling between the view and
view model.

Creating a view defined as a data template

A view can be defined as a data template and associated with a view model type.
Data templates can be defined as resources, or they can be defined inline within the control
that will display the view model. The content of the control is the view model instance, and
the data template is used to visually represent it. This technique is an example of a situation
in which the view model is instantiated first, followed by the creation of the view.

Automatically creating a view model with a view model locator

A view model locator is a custom class that manages the instantiation of view
models and their association to views. In the eShopOnContainers mobile app, the View
Mode Locator class has an attached property, Auto Wire ViewModel, that's used to associate
view models with views. In the view's XAML, this attached property is set to true to
indicate that the view model should be automatically connected to the view, as shown in the
following code example:

viewModelBase:ViewModelLocator.AutoWireViewModel="true"

The AutoWireViewModel property is a bindable property that's initialized to false,


and when its value changes the OnAutoWireViewModelChanged event handler is called.

26
Chapter 4 Model View ViewModel

This method resolves the view model for the view. The following code example shows how
this is achieved:

private static void OnAutoWireViewModelChanged(BindableObject bindable, object


oldValue, object n ewValue)
{
var view = bindable as Element;
if (view == null)
{
return;
}
var viewType = view.GetType();
var viewName = viewType.FullName.Replace(".Views.", ".ViewModels.");
var viewAssemblyName = viewType.GetTypeInfo().Assembly.FullName;
var viewModelName = string.Format( CultureInfo.InvariantCulture,
"{0}Model, {1}", viewName, viewAssemblyName);
var viewModelType = Type.GetType(viewModelName);
if (viewModelType == null)
{
return;
}
var viewModel = _container.Resolve(viewModelType);
view.BindingContext = viewModel;
}

The OnAutoWireViewModelChanged method attempts to resolve the view model using a


convention based approach.
This convention assumes that:
 View models are in the same assembly as view types.
 Views are in a .Views child namespace.
 View models are in a ViewModels child namespace.
 View model names correspond with view names and end with "ViewModel".

27
Chapter 5 Advantages & Disadvantages

7 Advantages & Disadvantages

3.1. Advantages
 Fast App Development Cycle
The coding is based on C# language and .Net libraries.

 Native Applications
Sharing the code between the different platforms is an easy task, which helps us to shorten
the development lifecycle.

 Shared App Logic


Developers can share 75% of the code across the various operating systems.
Application Logic underlying the UI layer like input validation, web service calls, database
interactions, and backend enterprises integrations are coded once in C#.

 API Integration
An application programming interface is a computing interface exposed by a particular
software program, library, operating system or internet service, to allow third parties to use
the functionality of that software application. 

Xamarin binds the same APIs and UI controls which are used to build the iOS, Android, and
Mac apps in their respective platform-specific language. For Windows development,
Xamarin with Microsoft Visual Studio offers windows phone and windows applications.
Code is shared between iOS, Android, and Windows using the Portable Class Library (PCL)
and appropriate application architecture. With Xamarin, support is always there. These
unique binding technologies enable us to provide the support for the new feature as soon as
they come in the device's operating system. Click on the respective platform links for their
latest support packages for iOS 8 and Android (with wearable support).

28
Chapter 5 Advantages & Disadvantages

 Code that works on multiple platforms


Sometimes clients have a limited budget and decide to develop an app only on one platform.
This means the app’s source code will work only on iOS or only on Android. Developing an
app with Xamarin allows you to create code that works well across multiple platforms.

 Flawless UI
Xamarin provides strong design tools. Xamarin Studio and the Microsoft Visual Studio
environment help designers to create flawless UIs and user experiences.

 Based on C#
It’s very important to mention that Xamarin is a C#-based program. C# is a type-safe, pure
object-oriented programming language that’s flexible and easy to learn. That’s why working
with Xamarin doesn’t require extra coding effort.

 Supports many libraries


Another essential benefit of Xamarin is the ability to use a variety of libraries. While React
Native doesn’t allow developers to use CSS libraries, Xamarin lets developers implement the
most complicated functionality with minimal effort.

 Effective offline applications


There are many situations when people don’t have an internet connection and need to use a
mobile app urgently. So offline applications come in handy. Xamarin is a perfect tool to
develop an effective mobile application that doesn’t require an internet connection.

 Works on Mac and Windows


When you want to make some changes in native app code, you need to choose the right
development environment for the app. On the other hand, developing code and making
changes to code with Xamarin doesn’t require switching to a specific environment. Xamarin
works on Mac as well as Windows. This is very convenient for mobile app developers as it
saves a lot of developer hours.

29
Chapter 5 Advantages & Disadvantages

 Benefits of Xamarin.Forms
It would be unfair not to mention the advantages of Xamarin.Forms, as it’s such a great
framework. When developers want to design views and use them for many platforms, they
prefer to use Xamarin.Forms over Xamarin Native.

Want to know a secret? Without Xamarin.Forms, developers would need to learn all the
native UI frameworks, which is difficult and time-consuming. Xamarin.Forms allows
developer to avoid this difficulty and design views quicker.

 Matches native standards


It’s worth mentioning that the UI greatly influences the user experience. That’s why it’s
important to choose a tool that will develop a mobile app that matches native standards.
Using Xamarin.Forms, developers can be sure their mobile app will be convenient for
Android, iOS, and Windows Phone users.

 Helpful for .Net developers


Xamarin is a C#-based program, so .Net developers can use Xamarin without making too
much effort to learn a new technology.

Let me explain. Most developers that use C# use .Net as well because Microsoft’s
implementation of C# is integrated with the .Net framework. That’s why I can be 100% sure
that Xamarin can easily be used by .Net developers.

 Integrated testing environment


Now it’s time to talk about Test Cloud. While most mobile apps are tested after development
has finished or just before submitting to the app store, Xamarin Test Cloud allows you to test
mobile applications continuously during development. As a result, developers get flawless
source code. With Xamarin, you can easily test your mobile app on different devices. It
would be nearly impossible to buy all the mobile phones in order to test a new mobile app,
but with Test Cloud you don’t have to cover these expenses.

 Saves money

30
Chapter 5 Advantages & Disadvantages

Above all, it’s pertinent to remember that when developing a Xamarin-based mobile app you
get a mobile application for multiple platforms, as Xamarin allows you to reuse 96% of the
source code. As a result, you’ll save money by getting at least three mobile apps: for
Android, for iOS, and for Windows Phone. Xamarin is a perfect solution for business owners
that value their time and money.

5.2 Disadvantages
 Unavoidable Software Overheads
Despite all the facts that Xamarin Mobile Application Development saves time by creating a
single app for the entire platform. On the other hand, it also involves in the linkage of the
code and references between the target OS environment of different devices in use, and .Net
frameworks show that this increases the time taken in the initiation and in downloading the
apps.

 Time-Consuming Nature of UI development


Time becomes an essential thing in UI development on the platform of Xamarin. Xamarin
offers the facility to reuse the code across the target of the device platform. It is hard to
create a portable version of the core UI. That is why Xamarin App Development experts
thoroughly perform some portion of coding for an independent platform, which is a time-
consuming process.

 Issues of App file size


With consuming more time, Xamarin takes more space in storing the app file size because
of the usage of the general use of Xamarin's core libraries and functionality of the app stores
with the wrong app file size. The size margin in the store may range from 3MB to 15MB.

31
Chapter 6 Conclusion

8 Conclusion

 Xamarin is also known as the king of cross-platform app development.

 The rich features and resulting benefits of all points towards the cross-platform
native applications.
 In addition to the advantages of the Xamarin, it boasts up the ever-growing
community of 70,000 plus developers who are continuously collaborating and
enhancing the software.

32
Chapter 6 Conclusion

References
https://docs.microsoft.com/en-us/xamarin/
https://www.javatpoint.com/xamarin

33

You might also like