Xamarin.Forms Notes for Professionalsπ Quay lαΊ‘i trang tαΊ£i sΓ‘ch pdf ebook Xamarin.Forms Notes for ProfessionalsEbooksNhΓ³m Zalo
Notes for Professionals Xamarin
Xamarin.Forms
.Forms
Notes for Professionals
100+ pages
of professional hints and tricks
GoalKicker.com Free Programming Books
Disclaimer
This is an unoξ€cial free book created for educational purposes and is not aξ€liated with oξ€cial Xamarin.Forms group(s) or company(s). All trademarks and registered trademarks are
the property of their respective owners
Contents
About ................................................................................................................................................................................... 1 Chapter 1: Getting started with Xamarin.Forms ........................................................................................... 2 Section 1.1: Installation (Visual Studio) ......................................................................................................................... 2 Section 1.2: Hello World Xamarin Forms: Visual Studio ............................................................................................. 4 Chapter 2: Why Xamarin Forms and When to use Xamarin Forms .................................................... 7 Section 2.1: Why Xamarin Forms and When to use Xamarin Forms ....................................................................... 7 Chapter 3: Xamarin Forms Layouts .................................................................................................................... 8 Section 3.1: AbsoluteLayout .......................................................................................................................................... 8 Section 3.2: Grid ........................................................................................................................................................... 10 Section 3.3: ContentPresenter .................................................................................................................................... 11 Section 3.4: ContentView ............................................................................................................................................ 12 Section 3.5: ScrollView ................................................................................................................................................ 13 Section 3.6: Frame ....................................................................................................................................................... 14 Section 3.7: TemplatedView ....................................................................................................................................... 14 Section 3.8: RelativeLayout ........................................................................................................................................ 15 Section 3.9: StackLayout ............................................................................................................................................ 16 Chapter 4: Xamarin Relative Layout ............................................................................................................... 19 Section 4.1: Box after box ........................................................................................................................................... 19 Section 4.2: Page with an simple label on the middle ............................................................................................. 21 Chapter 5: Navigation in Xamarin.Forms ....................................................................................................... 23 Section 5.1: NavigationPage flow with XAML ............................................................................................................ 23 Section 5.2: NavigationPage flow .............................................................................................................................. 24 Section 5.3: Master Detail Navigation ....................................................................................................................... 25 Section 5.4: Using INavigation from view model ..................................................................................................... 26 Section 5.5: Master Detail Root Page ........................................................................................................................ 28 Section 5.6: Hierarchical navigation with XAML ....................................................................................................... 29 Section 5.7: Modal navigation with XAML ................................................................................................................. 31 Chapter 6: Xamarin.Forms Page ........................................................................................................................ 32 Section 6.1: TabbedPage ............................................................................................................................................ 32 Section 6.2: ContentPage ........................................................................................................................................... 33 Section 6.3: MasterDetailPage ................................................................................................................................... 34 Chapter 7: Xamarin.Forms Cells ......................................................................................................................... 36 Section 7.1: EntryCell ................................................................................................................................................... 36 Section 7.2: SwitchCell ................................................................................................................................................. 36 Section 7.3: TextCell .................................................................................................................................................... 37 Section 7.4: ImageCell ................................................................................................................................................. 38 Section 7.5: ViewCell .................................................................................................................................................... 39 Chapter 8: Xamarin.Forms Views ....................................................................................................................... 41 Section 8.1: Button ....................................................................................................................................................... 41 Section 8.2: DatePicker ............................................................................................................................................... 42 Section 8.3: Entry ......................................................................................................................................................... 43 Section 8.4: Editor ........................................................................................................................................................ 43 Section 8.5: Image ....................................................................................................................................................... 44 Section 8.6: Label ........................................................................................................................................................ 45 Chapter 9: Using ListViews ..................................................................................................................................... 47 Section 9.1: Pull to Refresh in XAML and Code behind ............................................................................................ 47
Chapter 10: Display Alert ........................................................................................................................................ 48 Section 10.1: DisplayAlert ............................................................................................................................................ 48 Section 10.2: Alert Example with only one button and action ................................................................................. 49
Chapter 11: Accessing native features with DependencyService ....................................................... 50 Section 11.1: Implementing text-to-speech ................................................................................................................ 50 Section 11.2: Getting Application and Device OS Version Numbers - Android & iOS - PCL ................................. 53
Chapter 12: DependencyService ......................................................................................................................... 55 Section 12.1: Android implementation ........................................................................................................................ 55 Section 12.2: Interface ................................................................................................................................................. 56 Section 12.3: iOS implementation ............................................................................................................................... 56 Section 12.4: Shared code ........................................................................................................................................... 57
Chapter 13: Custom Renderers ............................................................................................................................ 58 Section 13.1: Accessing renderer from a native project ........................................................................................... 58 Section 13.2: Rounded label with a custom renderer for Frame (PCL & iOS parts) ............................................. 58 Section 13.3: Custom renderer for ListView .............................................................................................................. 59 Section 13.4: Custom Renderer for BoxView ............................................................................................................. 61 Section 13.5: Rounded BoxView with selectable background color ....................................................................... 65
Chapter 14: Caching .................................................................................................................................................. 68 Section 14.1: Caching using Akavache ....................................................................................................................... 68 Chapter 15: Gestures ................................................................................................................................................. 70 Section 15.1: Make an Image tappable by adding a TapGestureRecognizer ....................................................... 70 Section 15.2: Gesture Event ......................................................................................................................................... 70 Section 15.3: Zoom an Image with the Pinch gesture .............................................................................................. 78 Section 15.4: Show all of the zoomed Image content with the PanGestureRecognizer ....................................... 78 Section 15.5: Tap Gesture ........................................................................................................................................... 79 Section 15.6: Place a pin where the user touched the screen with MR.Gestures .................................................. 79 Chapter 16: Data Binding ........................................................................................................................................ 81 Section 16.1: Basic Binding to ViewModel .................................................................................................................. 81 Chapter 17: Working with Maps ........................................................................................................................... 83 Section 17.1: Adding a map in Xamarin.Forms (Xamarin Studio) ........................................................................... 83 Chapter 18: Custom Fonts in Styles ................................................................................................................... 92 Section 18.1: Accessing custom Fonts in Syles .......................................................................................................... 92 Chapter 19: Push Notifications ............................................................................................................................. 94 Section 19.1: Push notifications for Android with Azure ........................................................................................... 94 Section 19.2: Push notifications for iOS with Azure .................................................................................................. 96 Section 19.3: iOS Example ........................................................................................................................................... 99 Chapter 20: Eξ£ects .................................................................................................................................................. 101 Section 20.1: Adding platform specific Eξ£ect for an Entry control ...................................................................... 101 Chapter 21: Triggers & Behaviours .................................................................................................................. 105 Section 21.1: Xamarin Forms Trigger Example ....................................................................................................... 105 Section 21.2: Multi Triggers ....................................................................................................................................... 106 Chapter 22: AppSettings Reader in Xamarin.Forms .............................................................................. 107 Section 22.1: Reading app.config file in a Xamarin.Forms Xaml project ............................................................. 107 Chapter 23: Creating custom controls ........................................................................................................... 108 Section 23.1: Label with bindable collection of Spans ........................................................................................... 108 Section 23.2: Implementing a CheckBox Control ................................................................................................... 110 Section 23.3: Create an Xamarin Forms custom input control (no native required) ......................................... 116 Section 23.4: Creating a custom Entry control with a MaxLength property ....................................................... 118
Section 23.5: Creating custom Button ..................................................................................................................... 119 Chapter 24: Working with local databases ................................................................................................ 121 Section 24.1: Using SQLite.NET in a Shared Project ............................................................................................... 121 Section 24.2: Working with local databases using xamarin.forms in visual studio 2015 ................................... 123 Chapter 25: CarouselView - Pre-release version ..................................................................................... 133 Section 25.1: Import CarouselView .......................................................................................................................... 133 Section 25.2: Import CarouselView into a XAML Page .......................................................................................... 133 Chapter 26: Exception handling ........................................................................................................................ 135 Section 26.1: One way to report about exceptions on iOS .................................................................................... 135 Chapter 27: SQL Database and API in Xamarin Forms. ........................................................................ 137 Section 27.1: Create API using SQL database and implement in Xamarin forms, .............................................. 137 Chapter 28: Contact Picker - Xamarin Forms (Android and iOS) .................................................... 138 Section 28.1: contact_picker.cs ................................................................................................................................ 138 Section 28.2: MyPage.cs ........................................................................................................................................... 138 Section 28.3: ChooseContactPicker.cs .................................................................................................................... 139 Section 28.4: ChooseContactActivity.cs .................................................................................................................. 139 Section 28.5: MainActivity.cs .................................................................................................................................... 140 Section 28.6: ChooseContactRenderer.cs ............................................................................................................... 141 Chapter 29: Xamarin Plugin ................................................................................................................................ 144 Section 29.1: Media Plugin ........................................................................................................................................ 144 Section 29.2: Share Plugin ........................................................................................................................................ 146 Section 29.3: ExternalMaps ...................................................................................................................................... 147 Section 29.4: Geolocator Plugin ............................................................................................................................... 148 Section 29.5: Messaging Plugin ............................................................................................................................... 150 Section 29.6: Permissions Plugin .............................................................................................................................. 151 Chapter 30: OAuth2 ................................................................................................................................................. 155 Section 30.1: Authentication by using Plugin .......................................................................................................... 155 Chapter 31: MessagingCenter ............................................................................................................................. 157 Section 31.1: Simple example .................................................................................................................................... 157 Section 31.2: Passing arguments ............................................................................................................................. 157 Section 31.3: Unsubscribing ...................................................................................................................................... 158 Chapter 32: Generic Xamarin.Forms app lifecycle? Platform-dependant! ................................ 159
Section 32.1: Xamarin.Forms lifecycle is not the actual app lifecycle but a cross-platform representation of it .......................................................................................................................................................................... 159 Chapter 33: Platform-specific behaviour ..................................................................................................... 161 Section 33.1: Removing icon in navigation header in Anroid ................................................................................ 161 Section 33.2: Make label's font size smaller in iOS ................................................................................................ 161 Chapter 34: Platform specific visual adjustments .................................................................................. 163 Section 34.1: Idiom adjustments ............................................................................................................................... 163 Section 34.2: Platform adjustments ........................................................................................................................ 163 Section 34.3: Using styles ......................................................................................................................................... 164 Section 34.4: Using custom views ............................................................................................................................ 164 Chapter 35: Dependency Services ................................................................................................................... 165 Section 35.1: Access Camera and Gallery ............................................................................................................... 165 Chapter 36: Unit Testing ....................................................................................................................................... 166 Section 36.1: Testing the view models ..................................................................................................................... 166 Chapter 37: BDD Unit Testing in Xamarin.Forms ..................................................................................... 172 Section 37.1: Simple Specflow to test commands and navigation with NUnit Test Runner .............................. 172
Section 37.2: Advanced Usage for MVVM .............................................................................................................. 174 Credits ............................................................................................................................................................................ 175 You may also like ...................................................................................................................................................... 176
About
Please feel free to share this PDF with anyone for free,
latest version of this book can be downloaded from:
https://goalkicker.com/XamarinFormsBook
This Xamarin.Forms Notes for Professionals book is compiled from Stack Overflow Documentation, the content is written by the beautiful people at Stack Overflow. Text content is released under Creative Commons BY-SA, see credits at the end of this book whom contributed to the various chapters. Images may be copyright of their respective owners unless otherwise specified
This is an unofficial free book created for educational purposes and is not
affiliated with official Xamarin.Forms group(s) or company(s) nor Stack Overflow. All trademarks and registered trademarks are the property of their respective company owners
The information presented in this book is not guaranteed to be correct nor accurate, use at your own risk
Please send feedback and corrections to web@petercv.com
GoalKicker.com β Xamarin.Forms Notes for Professionals 1
Chapter 1: Getting started with
Xamarin.Forms
Version Release Date
3.0.0 2018-05-07
2.5.0 2017-11-15
2.4.0 2017-09-27
2.3.1 2016-08-03
2.3.0-hotfix1 2016-06-29
2.3.0 2016-06-16
2.2.0-hotfix1 2016-05-30
2.2.0 2016-04-27
2.1.0 2016-03-13
2.0.1 2016-01-20
2.0.0 2015-11-17
1.5.1 2016-10-20
1.5.0 2016-09-25
1.4.4 2015-07-27
1.4.3 2015-06-30
1.4.2 2015-04-21
1.4.1 2015-03-30
1.4.0 2015-03-09
1.3.5 2015-03-02
1.3.4 2015-02-17
1.3.3 2015-02-09
1.3.2 2015-02-03
1.3.1 2015-01-04
1.3.0 2014-12-24
1.2.3 2014-10-02
1.2.2 2014-07-30
1.2.1 2014-07-14
1.2.0 2014-07-11
1.1.1 2014-06-19
1.1.0 2014-06-12
1.0.1 2014-06-04
Section 1.1: Installation (Visual Studio)
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 Windows Phone. 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.
Xamarin Plugin for Visual Studio
To get started with Xamarin.Forms for Visual Studio you need to have the Xamarin plugin itself. The easiest way to have it installed is to download and install the latest Visual Studio.
GoalKicker.com β Xamarin.Forms Notes for Professionals 2
If you already have the latest Visual Studio installed, go to Control Panel > Programs and Features, right click on Visual Studio, and click Change. When the installer opens, click on Modify, and select the cross-platform mobile development tools:
You can also select to install the Android SDK:
Uncheck it if you already have the SDK installed. You will be able to setup Xamarin to use existing Android SDK later. Xamarin.Forms
Xamarin.Forms is a set of libraries for your Portable Class library and native assemblies. The Xamarin.Forms library itself is available as a NuGet package. To add it to your project just use the regular Install-Package command of the Package Manager Console:
Install-Package Xamarin.Forms
for all of your initial assemblies (for example MyProject, MyProject.Droid and MyProject.iOS). The easiest way to get started with Xamarin.Forms is to create an empty project in Visual Studio:
GoalKicker.com β Xamarin.Forms Notes for Professionals 3
As you can see there are 2 available options to create the blank app -- Portable and Shared. I recommend you to get started with Portable one because it's the most commonly used in the real world (differences and more explanation to be added).
After creating the project make sure you're using the latest Xamarin.Forms version as your initial template may contain the old one. Use your Package Manager Console or Manage NuGet Packages option to upgrade to the latest Xamarin.Forms (remember it's just a NuGet package).
While the Visual Studio Xamarin.Forms templates will create an iOS platform project for you, you will need to connect Xamarin to a Mac build host to be able to run these projects on the iOS Simulator or physical devices.
Section 1.2: Hello World Xamarin Forms: Visual Studio
After successfully installing Xamarin as described in the first example, it's time to launch the first sample application.
Step 1: Creating a new Project.
In Visual Studio, choose New -> Project -> Visual C# -> Cross-Platform -> Blank App (Xamarin.Forms Portable)
Name the app "Hello World" and select the location to create the project and click OK. This will create a solution for you which contains three projects:
1. HelloWorld (this is where your logic and views is placed, i.e. the portable project)
2. HelloWorld.Droid (the Android project)
3. HelloWorld.iOS (the iOS project)
GoalKicker.com β Xamarin.Forms Notes for Professionals 4
Step 2: Investigating the sample
Having created the solution, a sample application will be ready to be deployed. Open the App.cs located in the root of the portable project and investigate the code. As seen below, the Contents of the sample is a StackLayout which contains a Label:
using Xamarin.Forms;
namespace Hello_World
{
public class App : Application
{
public App()
{
// The root page of your application
MainPage = new ContentPage
{
Content = new StackLayout
{
VerticalOptions = LayoutOptions.Center,
Children = {
new Label {
HorizontalTextAlignment = TextAlignment.Center, Text = "Welcome to Xamarin Forms!"
}
}
}
};
}
protected override void OnStart()
GoalKicker.com β Xamarin.Forms Notes for Professionals 5
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
}
Step 3: Launching the application
Now simply right-click the project you want to start (HelloWorld.Droid or HelloWorld.iOS) and click Set as StartUp Project. Then, in the Visual Studio toolbar, click the Start button (the green triangular button that resembles a Play button) to launch the application on the targeted simulator/emulator.
GoalKicker.com β Xamarin.Forms Notes for Professionals 6
Chapter 2: Why Xamarin Forms and When to use Xamarin Forms
Section 2.1: Why Xamarin Forms and When to use Xamarin Forms
Xamarin is becoming more and more popular - it is hard to decide when to use Xamarin.Forms and when Xamarin.Platform (so Xamarin.iOS and Xamarin.Android).
First of all you should know for what kind of applications you can use Xamarin.Forms:
1. Prototypes - to visualize how your application will look on the different devices.
2. Applications which not require platform specific functionality (like APIs) - but here please note that Xamarin is working busily to provide as many cross-platform compatibility as possible.
3. Applications where code sharing is crucial - more important than UI.
4. Applications where data displayed is more important than advanced functionality
There are also many other factors:
1. Who will be responsible for application development - if your team consists of experienced mobile developers they will be able to handle Xamarin.Forms easily. But if you have one developer per platform (native development) Forms can be bigger challenge.
2. Please also note that with Xamarin.Forms you can still encounter some issues sometimes - Xamarin.Forms platform is still being improved.
3. Fast development is sometimes very important - to reduce costs and time you can decide to use Forms.
4. When developing enterprise applications without any advanced functionality it is better to use Xamarin.Forms - it enables you to share mode code not event in mobile area but in general. Some portions of code can be shared across many platforms.
You should not use Xamarin.Forms when:
1. You have to create custom functionality and and access platform specific APIs
2. You have to create custom UI for the mobile application
3. When some functionality is not ready for Xamarin.Forms (like some specific behaviour on the mobile device)
4. Your team consists of platform specific mobile developers (mobile development in Java and/or Swift/Objective C)
GoalKicker.com β Xamarin.Forms Notes for Professionals 7
Chapter 3: Xamarin Forms Layouts Section 3.1: AbsoluteLayout
AbsoluteLayout positions and sizes child elements proportional to its own size and position or by absolute values. Child views may be positioned and sized using proportional values or static values, and proportional and static values can be mixed.
A definition of an AbsoluteLayout in XAML looks like this:
The same layout would look like this in code:
Title = "Absolute Layout Exploration - Code";
var layout = new AbsoluteLayout();
var centerLabel = new Label {
Text = "I'm centered on iPhone 4 but no other device.",
LineBreakMode = LineBreakMode.WordWrap};
AbsoluteLayout.SetLayoutBounds (centerLabel, new Rectangle (115, 159, 100, 100));
GoalKicker.com β Xamarin.Forms Notes for Professionals 8
// No need to set layout flags, absolute positioning is the default
var bottomLabel = new Label { Text = "I'm bottom center on every device.", LineBreakMode = LineBreakMode.WordWrap };
AbsoluteLayout.SetLayoutBounds (bottomLabel, new Rectangle (.5, 1, .5, .1)); AbsoluteLayout.SetLayoutFlags (bottomLabel, AbsoluteLayoutFlags.All);
var rightBox = new BoxView{ Color = Color.Olive };
AbsoluteLayout.SetLayoutBounds (rightBox, new Rectangle (1, .5, 25, 100));
AbsoluteLayout.SetLayoutFlags (rightBox, AbsoluteLayoutFlags.PositionProportional);
var leftBox = new BoxView{ Color = Color.Red };
AbsoluteLayout.SetLayoutBounds (leftBox, new Rectangle (0, .5, 25, 100));
AbsoluteLayout.SetLayoutFlags (leftBox, AbsoluteLayoutFlags.PositionProportional);
var topBox = new BoxView{ Color = Color.Blue };
AbsoluteLayout.SetLayoutBounds (topBox, new Rectangle (.5, 0, 100, 25));
AbsoluteLayout.SetLayoutFlags (topBox, AbsoluteLayoutFlags.PositionProportional);
var twoFlagsBox = new BoxView{ Color = Color.Blue };
AbsoluteLayout.SetLayoutBounds (topBox, new Rectangle (.5, 0, 1, 25));
AbsoluteLayout.SetLayoutFlags (topBox, AbsoluteLayoutFlags.PositionProportional | AbsoluteLayout.WidthProportional);
layout.Children.Add (bottomLabel);
layout.Children.Add (centerLabel);
layout.Children.Add (rightBox);
layout.Children.Add (leftBox);
layout.Children.Add (topBox);
The AbsoluteLayout control in Xamarin.Forms allows you to specify where exactly on the screen you want the child elements to appear, as well as their size and shape (bounds).
There are a few different ways to set the bounds of the child elements based on the AbsoluteLayoutFlags enumeration that are used during this process. The AbsoluteLayoutFlags enumeration contains the following values:
All: All dimensions are proportional.
HeightProportional: Height is proportional to the layout.
None: No interpretation is done.
PositionProportional: Combines XProportional and YProportional.
SizeProportional: Combines WidthProportional and HeightProportional.
WidthProportional: Width is proportional to the layout.
XProportional: X property is proportional to the layout.
YProportional: Y property is proportional to the layout.
The process of working with the layout of the AbsoluteLayout container may seem a little counterintuitive at first, but with a little use it will become familiar. Once you have created your child elements, to set them at an absolute position within the container you will need to follow three steps. You will want to set the flags assigned to the elements using the AbsoluteLayout.SetLayoutFlags() method. You will also want to use the AbsoluteLayout.SetLayoutBounds() method to give the elements their bounds. Finally, you will want to add the child elements to the Children collection. Since Xamarin.Forms is an abstraction layer between Xamarin and the device-specific implementations, the positional values can be independent of the device pixels. This is where the layout flags mentioned previously come into play. You can choose how the layout process of the Xamarin.Forms controls should interpret the values you define.
GoalKicker.com β Xamarin.Forms Notes for Professionals 9
Section 3.2: Grid
A layout containing views arranged in rows and columns.
This is a typical Grid definition in XAML.
The same Grid defined in code looks like this:
var grid = new Grid();
grid.RowDefinitions.Add (new RowDefinition { Height = new GridLength(2, GridUnitType.Star) }); grid.RowDefinitions.Add (new RowDefinition { Height = new GridLength (1, GridUnitType.Star) }); grid.RowDefinitions.Add (new RowDefinition { Height = new GridLength(200)}); grid.ColumnDefinitions.Add (new ColumnDefinition{ Width = new GridLength (200) });
To add items to the grid: In XAML:
GoalKicker.com β Xamarin.Forms Notes for Professionals 10
<--DEFINITIONS...--!>
In C# code:
var grid = new Grid();
//DEFINITIONS...
var topLeft = new Label { Text = "Top Left" };
var topRight = new Label { Text = "Top Right" };
var bottomLeft = new Label { Text = "Bottom Left" };
var bottomRight = new Label { Text = "Bottom Right" };
grid.Children.Add(topLeft, 0, 0);
grid.Children.Add(topRight, 0, 1);
grid.Children.Add(bottomLeft, 1, 0);
grid.Children.Add(bottomRight, 1, 1);
For Height and Width a number of units are available.
Auto β automatically sizes to fit content in the row or column. Specified as GridUnitType.Auto in C# or as Auto in XAML.
Proportional β sizes columns and rows as a proportion of the remaining space. Specified as a value and GridUnitType.Star in C# and as #* in XAML, with # being your desired value. Specifying one row/column with * will cause it to fill the available space.
Absolute β sizes columns and rows with specific, fixed height and width values. Specified as a value and GridUnitType.Absolute in C# and as # in XAML, with # being your desired value.
Note: The width values for columns are set as Auto by default in Xamarin.Forms, which means that the width is determined from the size of the children. Note that this differs from the implementation of XAML on Microsoft platforms, where the default width is *, which will fill the available space.
Section 3.3: ContentPresenter
A layout manager for templated views. Used within a ControlTemplate to mark where the content to be presented appears.
GoalKicker.com β Xamarin.Forms Notes for Professionals 11
Section 3.4: ContentView
An element with a single content. ContentView has very little use of its own. Its purpose is to serve as a base class for user-defined compound views.
XAML
Code
GoalKicker.com β Xamarin.Forms Notes for Professionals 12
var contentView = new ContentView {
Content = new Label {
Text = "Hi, I'm a simple Label inside of a simple ContentView",
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center
}
};
Section 3.5: ScrollView
An element capable of scrolling if it's Content requires.
ScrollView contains layouts and enables them to scroll offscreen. ScrollView is also used to allow views to automatically move to the visible portion of the screen when the keyboard is showing.
Note: ScrollViews should not be nested. In addition, ScrollViews should not be nested with other controls that provide scrolling, like ListView and WebView.
A ScrollView is easy to define. In XAML:
The same definition in code:
var scroll = new ScrollView();
Content = scroll;
var stack = new StackLayout();
stack.Children.Add(new BoxView { BackgroundColor = Color.Red, HeightRequest = 600, WidthRequest = 600 });
GoalKicker.com β Xamarin.Forms Notes for Professionals 13
stack.Children.Add(new Entry());
Section 3.6: Frame
An element containing a single child, with some framing options. Frame have a default
Xamarin.Forms.Layout.Padding of 20.
XAML
Code
var frameView = new Frame {
Content = new Label {
Text = "I've been framed!",
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center
},
OutlineColor = Color.Red
};
Section 3.7: TemplatedView
An element that displays content with a control template, and the base class for ContentView.
GoalKicker.com β Xamarin.Forms Notes for Professionals 14
Section 3.8: RelativeLayout
A Layout that uses Constraints to layout its children.
RelativeLayout is used to position and size views relative to properties of the layout or sibling views. Unlike AbsoluteLayout, RelativeLayout does not have the concept of the moving anchor and does not have facilities for positioning elements relative to the bottom or right edges of the layout. RelativeLayout does support positioning elements outside of its own bounds.
A RelativeLayout in XAML, is like this:
The same layout can be accomplished with this code:
layout.Children.Add (redBox, Constraint.RelativeToParent ((parent) => {
return parent.X;
}), Constraint.RelativeToParent ((parent) => {
return parent.Y * .15;
}), Constraint.RelativeToParent((parent) => {
return parent.Width;
}), Constraint.RelativeToParent((parent) => {
return parent.Height * .8;
}));
layout.Children.Add (blueBox, Constraint.RelativeToView (redBox, (Parent, sibling) => { return sibling.X + 20;
}), Constraint.RelativeToView (blueBox, (parent, sibling) => {
return sibling.Y + 20;
}), Constraint.RelativeToParent((parent) => {
return parent.Width * .5;
}), Constraint.RelativeToParent((parent) => {
return parent.Height * .5;
}));
Section 3.9: StackLayout
StackLayout organizes views in a one-dimensional line ("stack"), either horizontally or vertically. Views in a StackLayout can be sized based on the space in the layout using layout options. Positioning is determined by the order views were added to the layout and the layout options of the views.
GoalKicker.com β Xamarin.Forms Notes for Professionals 16
Usage in XAML
Usage in code
StackLayout stackLayout = new StackLayout
{
Spacing =0,
VerticalOptions = LayoutOptions.FillAndExpand,
Children =
{
new Label
{
Text = "StackLayout",
HorizontalOptions = LayoutOptions.Start
},
new Label
{
Text = "stacks its children",
HorizontalOptions = LayoutOptions.Center
},
new Label
{
Text = "vertically",
HorizontalOptions = LayoutOptions.End
},
new Label
{
Text = "by default,",
HorizontalOptions = LayoutOptions.Center
},
new Label
{
Text = "but horizontal placement",
HorizontalOptions = LayoutOptions.Start
},
new Label
GoalKicker.com β Xamarin.Forms Notes for Professionals 17
{
Text = "can be controlled with",
HorizontalOptions = LayoutOptions.Center
},
new Label
{
Text = "the HorizontalOptions property.", HorizontalOptions = LayoutOptions.End
},
new Label
{
Text = "An Expand option allows one or more children " + "to occupy the an area within the remaining " + "space of the StackLayout after it's been sized " + "to the height of its parent.",
VerticalOptions = LayoutOptions.CenterAndExpand, HorizontalOptions = LayoutOptions.End
},
new StackLayout
{
Spacing = 0,
Orientation = StackOrientation.Horizontal, Children =
{
new Label
{
Text = "Stacking",
},
new Label
{
Text = "can also be",
HorizontalOptions = LayoutOptions.CenterAndExpand },
new Label
{
Text = "horizontal.",
},
}
}
}
};
GoalKicker.com β Xamarin.Forms Notes for Professionals 18
Chapter 4: Xamarin Relative Layout Section 4.1: Box after box
public class MyPage : ContentPage
{
RelativeLayout _layout;
BoxView centerBox;
BoxView rightBox;
BoxView leftBox;
BoxView topBox;
BoxView bottomBox;
const int spacing = 10;
const int boxSize = 50;
public MyPage()
{
_layout = new RelativeLayout();
centerBox = new BoxView
{
BackgroundColor = Color.Black
};
rightBox = new BoxView
{
BackgroundColor = Color.Blue,
//You can both set width and hight here
GoalKicker.com β Xamarin.Forms Notes for Professionals 19
//Or when adding the control to the layout
WidthRequest = boxSize,
HeightRequest = boxSize
};
leftBox = new BoxView
{
BackgroundColor = Color.Yellow,
WidthRequest = boxSize,
HeightRequest = boxSize
};
topBox = new BoxView
{
BackgroundColor = Color.Green,
WidthRequest = boxSize,
HeightRequest = boxSize
};
bottomBox = new BoxView
{
BackgroundColor = Color.Red,
WidthRequest = boxSize,
HeightRequest = boxSize
};
//First adding center box since other boxes will be relative to center box _layout.Children.Add(centerBox,
//Constraint for X, centering it horizontally
//We give the expression as a paramater, parent is our layout in this case Constraint.RelativeToParent(parent => parent.Width / 2 - boxSize / 2), //Constraint for Y, centering it vertically
Constraint.RelativeToParent(parent => parent.Height / 2 - boxSize / 2), //Constraint for Width
Constraint.Constant(boxSize),
//Constraint for Height
Constraint.Constant(boxSize));
_layout.Children.Add(leftBox,
//The x constraint will relate on some level to centerBox
//Which is the first parameter in this case
//We both need to have parent and centerBox, which will be called sibling, //in our expression parameters
//This expression will be our second paramater
Constraint.RelativeToView(centerBox, (parent, sibling) => sibling.X - spacing - boxSize),
//Since we only need to move it left,
//it's Y constraint will be centerBox' position at Y axis
Constraint.RelativeToView(centerBox, (parent, sibling) => sibling.Y) //No need to define the size constraints
//Since we initialize them during instantiation
);
_layout.Children.Add(rightBox,
//The only difference hear is adding spacing and boxSize instead of subtracting them Constraint.RelativeToView(centerBox, (parent, sibling) => sibling.X + spacing + boxSize),
Constraint.RelativeToView(centerBox, (parent, sibling) => sibling.Y) );
_layout.Children.Add(topBox,
//Since we are going to move it vertically this thime
GoalKicker.com β Xamarin.Forms Notes for Professionals 20
//We need to do the math on Y Constraint
//In this case, X constraint will be centerBox' position at X axis Constraint.RelativeToView(centerBox, (parent, sibling) => sibling.X), //We will do the math on Y axis this time
Constraint.RelativeToView(centerBox, (parent, sibling) => sibling.Y - spacing - boxSize)
);
_layout.Children.Add(bottomBox,
Constraint.RelativeToView(centerBox, (parent, sibling) => sibling.X), Constraint.RelativeToView(centerBox, (parent, sibling) => sibling.Y + spacing + boxSize)
);
Content = _layout;
}
}
Section 4.2: Page with an simple label on the middle
public class MyPage : ContentPage
{
RelativeLayout _layout;
Label MiddleText;
public MyPage()
{
_layout = new RelativeLayout();
MiddleText = new Label
{
GoalKicker.com β Xamarin.Forms Notes for Professionals 21
Text = "Middle Text"
};
MiddleText.SizeChanged += (s, e) =>
{
//We will force the layout so it will know the actual width and height of the label //Otherwise width and height of the label remains 0 as far as layout knows _layout.ForceLayout();
};
_layout.Children.Add(MiddleText
Constraint.RelativeToParent(parent => parent.Width / 2 - MiddleText.Width / 2), Constraint.RelativeToParent(parent => parent.Height / 2 - MiddleText.Height / 2));
Content = _layout;
}
}
GoalKicker.com β Xamarin.Forms Notes for Professionals 22
Chapter 5: Navigation in Xamarin.Forms Section 5.1: NavigationPage flow with XAML
App.xaml.cs file (App.xaml file is default, so skipped)
using Xamrin.Forms
namespace NavigationApp
{
public partial class App : Application
{
public static INavigation GlobalNavigation { get; private set; }
public App()
{
InitializeComponent();
var rootPage = new NavigationPage(new FirstPage());
GlobalNavigation = rootPage.Navigation;
MainPage = rootPage;
}
}
}
FirstPage.xaml file
In some cases you need to open the new page not in the current navigation but in the global one. For example, if your current page contains bottom menu, it will be visible when you push the new page in the current navigation. If you need the page to be opened over the whole visible content hiding the bottom menu and other current page's content, you need to push the new page as a modal into the global navigation. See App.GlobalNavigation property and the example below.
FirstPage.xaml.cs file
using System;
using Xamarin.Forms;
GoalKicker.com β Xamarin.Forms Notes for Professionals 23
namespace NavigationApp
{
public partial class FirstPage : ContentPage
{
public FirstPage()
{
InitializeComponent();
}
async void GoToSecondPageButtonClicked(object sender, EventArgs e) {
await Navigation.PushAsync(new SecondPage(), true); }
async void OpenGlobalModalPageButtonClicked(object sender, EventArgs e) {
await App.GlobalNavigation.PushModalAsync(new SecondPage(), true); }
}
}
SecondPage.xaml file (xaml.cs file is default, so skipped)
Section 5.2: NavigationPage flow
using System;
using Xamarin.Forms;
namespace NavigationApp
{
public class App : Application
{
public App()
{
MainPage = new NavigationPage(new FirstPage());
}
}
public class FirstPage : ContentPage
{
Label FirstPageLabel { get; set; } = new Label();
Button FirstPageButton { get; set; } = new Button();
public FirstPage()
{
Title = "First page";
GoalKicker.com β Xamarin.Forms Notes for Professionals 24
FirstPageLabel.Text = "This is the first page";
FirstPageButton.Text = "Navigate to the second page";
FirstPageButton.Clicked += OnFirstPageButtonClicked;
var content = new StackLayout();
content.Children.Add(FirstPageLabel);
content.Children.Add(FirstPageButton);
Content = content;
}
async void OnFirstPageButtonClicked(object sender, EventArgs e)
{
await Navigation.PushAsync(new SecondPage(), true);
}
}
public class SecondPage : ContentPage
{
Label SecondPageLabel { get; set; } = new Label();
public SecondPage()
{
Title = "Second page";
SecondPageLabel.Text = "This is the second page";
Content = SecondPageLabel;
}
}
}
Section 5.3: Master Detail Navigation
The code below shows how to perform asynchronous navigation when the app is in a MasterDetailPage context.
public async Task NavigateMasterDetail(Page page)
{
if (page == null)
{
return;
}
var masterDetail = App.Current.MainPage as MasterDetailPage;
if (masterDetail == null || masterDetail.Detail == null)
return;
var navigationPage = masterDetail.Detail as NavigationPage;
if (navigationPage == null)
{
masterDetail.Detail = new NavigationPage(page);
masterDetail.IsPresented = false;
return;
}
await navigationPage.Navigation.PushAsync(page);
navigationPage.Navigation.RemovePage(navigationPage.Navigation.NavigationStack[navigationPage.Navig ation.NavigationStack.Count - 2]);
GoalKicker.com β Xamarin.Forms Notes for Professionals 25
masterDetail.IsPresented = false;
}
Section 5.4: Using INavigation from view model First step is create navigation interface which we will use on view model:
public interface IViewNavigationService
{
void Initialize(INavigation navigation, SuperMapper navigationMapper); Task NavigateToAsync(object navigationSource, object parameter = null); Task GoBackAsync();
}
In Initialize method I use my custom mapper where I keep collection of pages types with associated keys.
public class SuperMapper
{
private readonly ConcurrentDictionary _typeToAssociateDictionary = new ConcurrentDictionary();
private readonly ConcurrentDictionary