2. AGENDA
• What is Xamarin?
• Environment setup
• Project structure
• Xamarin architecture
• XAML
• Elements & attributes, Naming, Data binding
• Page layouts
• StackLayout, Grid, RelativeLayout
• Lists
• Text lists, Pre-defined templates, Custom templates
3. WHAT IS XAMARIN?
• Microsoft’s cross-platform development
toolkit
• Designed to enable app development for
Android, iOS, Windows Mobile, & Windows
platforms.
• Xamarin performs cross-compilation rather
than being an interpreted language – it
provides performance near to native
applications.
• Leverages the power of the C# language and
the .Net Framework
4. ENVIRONMENT SETUP
1. Everything is handled through Microsoft’s
own development platform, Visual Studio.
2. Heading to
https://www.xamarin.com/download will let
you down load the free Visual Studio
Community Edition, with Xamarin support
pre-installed.
• If you already have VS, you can install Xamarin using
the dialog found at Tools Get Tools & Features…
3. Point Xamarin to your Android SDK using
Options search for “Android” Android
Settings
5. PROJECT CREATION
• Xamarin allows developers to write three kinds of
apps:
• Xamarin.Android: Write fully native Android apps using
C# instead of Java
• Xamarin.iOS: Write fully native iOS apps using C#
instead of Objective-C / Swift
• Xamarin.Forms: Write cross-platform apps
• Even when using Xamarin.Android & Xamarin.iOS,
code can be shared between them using a Shared
Project. Thus, most logic can be shared cross-
platform without code duplication, while
completely separate native UIs can be developed.
• To create any of these project types:
• File New Project Visual C# (either Android,
iOS, or Cross-Platform)
6. PROJECT CREATION
1. New project Cross-Platform Xamarin
Forms
2. Pick a location, choose a project & solution
name (they can be the same), and select
“create directory”
3. Select “Blank App”, pick your supported
platforms, pick Xamarin Forms for the UI
technology, and “Shared Project” for code
sharing.
7. PROJECT STRUCTURE
• MyFirstXamarinApp: A shared project. Anything in here will
be shared between all platforms. Xamarin Forms code and
shared classes go here.
• *.Android, *.iOS: Resources in here will be used only on
Android, iOS, and Windows platforms, respectively.
• The native projects have C# versions of the building blocks
for those platforms (i.e. Activity for Android, AppDelegate
for iOS). By default, in a Forms project, these load an
instance of the App class – which is the class defined by the
shared App.xaml.
• The first time you create a Xamarin project, you may see
“class not found” errors in your code – these will be
resolved the first time you build (right-click a project
build)
8. PROJECT STRUCTURE
Three main kinds of files to define a Xamarin.Forms
app:
• XAML
• Stands for “eXtensible Application Markup Language”
• An XML specification. Like HTML, allows developers to
define the visual structure of a particular page (screen)
of an app.
• Code-Behind
• A C# file implementing the behaviour for a particular
page (e.g. what happens when you click a button or
select an item in a list?)
• A XAML file and its associated code-behind are
compiled together into a single .Net class at runtime.
• Other classes
9. PROJECT STRUCTURE
• Xamarin Forms is built on top of the platform-
specific libraries, Xamarin.Android and
Xamarin.iOS.
• UI elements in Xamarin Forms are mapped to
native equivalents on the target platforms. If
Xamarin Forms is used exclusively to define
the UI, then we can achieve a 100% cross-
platform app.
• If we wish to provide platform-specific
features, we can do so by editing the
associated platform-specific project.
Xamarin Forms
Xamarin.Andr
oid
Xamarin.iOS
11. LIVE PLAYER
• Running / debugging the app in the Live Player:
1. Choose “Live Player” when running the app
2. Download the Xamarin Live Player app on iOS or
Android
3. Scan the provided QR code
• Live editing XAML:
1. Right-click the code window containing your XAML
2. Choose “Live Run”
3. When you save your changes, they should appear on
the device.
• As usual, how well this works depends on the
quality of the network connection between the
device and development machine.
12. RUNNING ON DEVICE
• Connect your device via USB and select it from the
run menu
• Any defined virtual machines will also appear here
• Click the play button – or use hotkeys (F5 to run,
Ctrl + F5 to debug)
• Your app will be built for the target platform and
deployed to the target device.
• Can take some time to build the first time (but not
as long as some other tools we’ve seen!)
• Usually very quick to load on concurrent runs
14. DEBUGGING
• Full debugging! Set breakpoints, step into /
over / out, run to cursor, view values of
current objects in memory, etc.
15. MAKING A NEW PAGE
1. Right-click shared project, click Add New
Item…
2. Select Xamarin.Forms Content Page
3. Name the file on the bottom (e.g.
GreetingPage.xaml)
4. Choose “Add”
5. Two files will be created:
1. GreetingPage.xaml – to define the visual structure
2. GreetingPage.xaml.cs – to define the behavior of the
page
16. THE XAML
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MyFirstXamarinApp.GreetingPage">
<ContentPage.Content>
<StackLayout>
<Label Text="Welcome to Xamarin.Forms!"
VerticalOptions="CenterAndExpand"
HorizontalOptions="CenterAndExpand" />
</StackLayout>
</ContentPage.Content>
</ContentPage>
This is a
ContentPage (for
diaplaying main
content)
The actual
content goes
here.
A StackLayout
arranges
children
vertically
(default) or
horizontally.
A Label displays
text.
The .Net class name of this
page. Will match the class
name of the code-behind.
17. THE CODE-BEHIND
using …
namespace MyFirstXamarinApp
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class GreetingPage : ContentPage
{
public GreetingPage ()
{
InitializeComponent ();
}
}
}
“using” similar to Java “import”
statements
Namespaces similar to Java packages –
except they are independent of folder
structure.
This is an
Attribute –
similar to
Java
annotations.
The class definition. “partial” means
that some of the class is defined in
this file, and some of it elsewhere
This class
extends
ContentPage.
In C#, there’s
no “extends”
or
“implements”
keywords –
you just use a
colon :
Constructor
Calling this method
will create and
display all on-screen
18. FIRST XAML EDITS
1. Remove the existing content in our page
2. Add a <Button> element as follows:
<Button HorizontalOptions="Center"
VerticalOptions="Center"
Text="Click Me!"
Clicked="Button_Clicked"></Button>
private void Button_Clicked(object sender, EventArgs e)
{
DisplayAlert("Alert Title", "Hello World", "Ok");
}
Define a
Button…
The button is centered
horizontally and vertically in
its parent
The button
will have the
text “Click
Me!”
When the button is clicked, a
method in the code-behind with this
name will be called.
This is the event
handler method in the
code-behind. When the method is called, “sender” will be the
button itself, and “e” will contain additional info
about the event.
Display an alert to
the user. Inherited
from ContentPage
19. RUNNING OUR HELLO WORLD
APP
1. Open App.xaml.cs (the code-behind for
App.xaml)
2. Change the MainPage property to point to a
new instance of GreetingPage
3. Run the app
namespace MyFirstXamarinApp
{
public partial class App : Application
{
public App ()
{
InitializeComponent();
MainPage = new GreetingPage();
}
…
}
}
20. XAMARIN ARCHITECTURE
• All Xamarin platforms are built on Mono – an
open-source version of Microsoft’s .Net
framework, for non-Windows platforms.
• Xamarin.Android – formerly known as “Mono
for Android”
• Xamarin.iOS – formerly known as “MonoTouch”
Xamarin Forms
Xamarin.Android Xamarin.iOS
Mono
21. XAMARIN ARCHITECTURE
• Mono for a particular platform provides:
• .Net Base Class Library (BCL): a collection of widely
used classes from the framework, well-known for
traditional .Net developers
• Native APIs for that particular platform
• The Native APIs are direct equivalents of
Android / iOS classes – but wrapped in C#. The
names of these classes will be familiar to
native developers for those platforms.
Xamarin Forms
Xamarin.Android Xamarin.iOS
.Net BCL .Net BCL
Native APIs Native APIs
22. XAMARIN.ANDROID
ARCHITECTURE
C# Code IL Mono Runtime
Compile
.Net Intermediate
Language (similar to
Java bytecode)
Native
Just-in-time (JIT)
Compilation
Happens at runtime.
Process similar to
standard .Net console,
desktop applications
23. XAMARIN.IOS ARCHITECTURE
• Different – because Apple doesn’t allow JIT
compilation!
• No “Mono Runtime” on iOS devices – everything’s
already native
• No JIT compiling – everything is compiled to Apple
machine code at build time.
C# Code IL
Compile
Mono IL
Native
+
Apple compiler,
ahead-of-time
(AOT)
24. XAMARIN.FORMS
ARCHITECTURE
• Xamarin.Forms.Core: Defines common code
and interfaces for Xamarin Forms components
• Implementation classes are provided by the
Android / iOS – specific libraries.
Xamarin Forms
Xamarin.Andr
oid
Xamarin.iOS
Xamarin.Forms.Core
Library
Xamarin.For
ms Android
impl
Xamarin.For
ms iOS impl
25. NAMING ELEMENTS
• Within XAML, we can give elements names using the x:Name
attribute. Remember the x:!
• We can now access the element with that name from the
code-behind!
• How? Setting the x:Name property results in the code
generation of the corresponding variable name, which will
be set at runtime when the XAML is read.
<StackLayout HorizontalOptions="Center" VerticalOptions="Center">
<Label Text="Hello World" x:Name="myLabel" />
<Slider ValueChanged="Slider_ValueChanged" />
</StackLayout>
private void Slider_ValueChanged(object sender, ValueChangedEventArgs e)
{
myLabel.Text = String.Format("Value is {0:F2}", e.NewValue);
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "0.0.0.0")]
private global::Xamarin.Forms.Label myLabel;
Generated code in GreetingPage.xaml.g.cs
26. DATA BINDING
• Allows us to bind the value of a property of one
object (usually a UI element) to the value of some
other property.
• When a bound property changes, its data source will
also change, and vice versa.
• Let’s bind our label’s Text property to our slider’s
Value property:
• This works, but our Label won’t be nicely
formatted.
<Label Text="{Binding Source={x:Reference mySlider}, Path=Value}" x:Name="myLabel" />
<Slider x:Name="mySlider" />
<Label Text="{Binding
Source={x:Reference mySlider},
Path=Value,
StringFormat='Value is {0:F2}'}" x:Name="myLabel" />
27. DATA BINDING
• We can also set a BindingContext for an
element, rather than individually set the
Source:
<Label BindingContext="{x:Reference mySlider}"
Text="{Binding
Path=Value,
StringFormat='Value is {0:F2}'}"
Opacity="{Binding
Path=Value }"
x:Name="myLabel" />
28. DATA BINDING
• BindingContext of a parent element is
inherited by all its descendants.
<StackLayout BindingContext="{x:Reference mySlider}"
HorizontalOptions="Center"
VerticalOptions="Center">
<BoxView Color="Red" Opacity="{Binding Value}" />
<Label Text="{Binding Value, StringFormat='Value is {0:F2}'}"
Opacity="{Binding Value}"
x:Name="myLabel" />
<Slider x:Name="mySlider" />
</StackLayout>
29. XAML COMPILATION
• XAML is not compiled by default – it is included in the
built package and parsed when needed.
• This behaviour is to promote backwards compatibility,
but we can enable XAML compilation to achieve several
benefits:
• Compile-time checking of XAML to detect erors
• Reduced loading time
• Reduced file size
• To do this, add the following Attribute to the
AssemblyInfo.cs file:
using Xamarin.Forms.Xaml;
…
[assembly: XamlCompilation (XamlCompilationOptions.Compile)]
30. PAGE LAYOUTS - STACKLAYOUT
• Layout child elements in a line – either vertical (default) or
horizontal
• Set the StackLayout’s Orientation property to change this.
• By default, StackLayout will expand to fill its parent
• We can change this behaviour by setting the VerticalOptions and / or
HorizontalOptions properties.
<StackLayout BackgroundColor="Yellow">
<Label Text="Label 1"/>
<Label Text="Label 2"/>
<Label Text="Label 3"/>
</StackLayout>
<StackLayout BackgroundColor="Yellow"
VerticalOptions="Center">
<Label Text="Label 1"/>
<Label Text="Label 2"/>
<Label Text="Label 3"/>
</StackLayout>
31. PAGE LAYOUTS - STACKLAYOUT
• Can set the Spacing between child elements
• Default value is 6, meaning a small amount of
spacing between child elements.
• Can set the Padding around child elements
• Default value is 0 each side
<StackLayout BackgroundColor="Yellow"
VerticalOptions="Center"
HorizontalOptions="Center"
Spacing="50"
Padding="10, 20, 30, 40">
<Label Text="Label 1" BackgroundColor="AliceBlue"/>
<Label Text="Label 2" BackgroundColor="AliceBlue"/>
<Label Text="Label 3" BackgroundColor="AliceBlue"/>
</StackLayout>
Padding left: 10
Padding top: 20
Paddin
g
right:
30
Padding bottom:
40
Spacing: 50
33. PAGE LAYOUTS - GRID
• Layout components in rows & columns
• Configurable spacing between elements
• RowSpacing and ColumnSpacing attributes
• Expands to fill entire parent by default
<Grid BackgroundColor="Yellow">
<Label Grid.Row="0" Grid.Column="0" Text="Label 1" BackgroundColor="LightGray"/>
<Label Grid.Row="0" Grid.Column="1" Text="Label 2" BackgroundColor="LightGray"/>
<Label Grid.Row="1" Grid.Column="0" Text="Label 3" BackgroundColor="LightGray"/>
<Label Grid.Row="1" Grid.Column="1" Text="Label 4" BackgroundColor="LightGray"/>
</Grid>
Since the parent is a Grid, our children
have extra attributes available, which
belong to the Grid.
35. PAGE LAYOUTS - GRID
• By default, all rows are the same size, and all columns
are the same size.
• Can change this using Grid.RowDefinitions and
Grid.ColumnDefinitions
• In the below example, the first row is 100 units tall, the
second row takes up 2/3 of the remaining space, and the last
row takes up 1/3 of the space.
<Grid BackgroundColor="Yellow"
RowSpacing="20"
ColumnSpacing="20"
Padding="20">
<Grid.RowDefinitions>
<RowDefinition Height="100"/>
<RowDefinition Height="2*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Label Grid.Row="0" Grid.Column="0" …/>
<Label Grid.Row="0" Grid.Column="1" …/>
<Label Grid.Row="1" Grid.Column="0" …/>
<Label Grid.Row="1" Grid.Column="1" …/>
<Label Grid.Row="2" Grid.Column="0" …/>
</Grid>
36. PAGE LAYOUTS - RELATIVE
• Allows us to specify the positions of elements
relative to parent and / or sibling elements.
• Width & Height constraints, relative to parent
• The following code means…
<RelativeLayout>
<BoxView Color="Red" x:Name="redBox"
RelativeLayout.WidthConstraint="{ConstraintExpression
Type=RelativeToParent,
Property=Width,
Factor=1}"
RelativeLayout.HeightConstraint="{ConstraintExpression
Type=RelativeToParent,
Property=Height,
Factor=0.3}"/>
</RelativeLayout>
Set the Width
to be 100% of
the parent’s
width
Set the Height
to be 30% of
the parent’s
height
37. PAGE LAYOUTS - RELATIVE
• Can define other constraints too:
• WidthConstraint, HeightConstraint
• XConstraint, YConstraint
• BoundsConstraint
• Can define relative to the properties of
siblings, e.g:
<RelativeLayout>
<BoxView Color="Red" x:Name="redBox" … />
<BoxView Color="LightGray"
RelativeLayout.YConstraint="{ConstraintExpression
Type=RelativeToView,
ElementName=redBox,
Property=Height,
Factor=1,
Constant=20}"/>
</RelativeLayout>
Set the Y value to be equal to
100% of the Height of the redBox,
plus 20.
For columns: The same, except Grid.ColumnDefinitions, and ColumnDefinition.
Definition can be “Auto” – meaning, wide / high enough to fit its children.