Mobile App Development with Xamarin Forms

This year the mobile app turns 10 years old. In this past decade, we have seen websites redesigned to scale and respond to a variety of mobile devices such as tablets and smartphones to provide a “like” mobile native app UI. There has been many frameworks developed such as Bootstrap, Foundation etc. to help aid designers and developers with the design of mobile responsive websites.

However, as the mobile app became more popular with the increase of sales on smartphones and tablets across the three main platforms, iOS, Android, and Windows this left existing design agencies, web designers and developers at a bit of a crossroads.  How to support the development of these mobile platforms whilst utilising the existing design and development skills of their team, without the need to invest time learning new programming languages like Java for Android, Objective-C for iOS and C# for Windows.

WHAT IS XAMARIN FORMS?

The answer to their problem was Xamarin Forms.  Xamarin Forms is a mobile application platform that comes bundled with Microsoft’s Visual Studio IDE available on both Windows and Mac. With Xamarin Forms, designers and developers could build native apps for iOS, Android and Windows from a single, shared C# codebase. Having spent time developing apps for clients with Xamarin Forms for the past 2 years I decided to create this article to provide web designers and web developers an insight into using Xamarin Forms to develop apps and some lessons learned during my time developing with it. With this article, I am going to assume you having a base level of a programming language or for designers a good understanding of HTML and CSS. OK, now that the formalities are out the way let us dive right in!

HOW XAMARIN FORMS WORKS

Xamarin Forms works by mapping the UI elements you create from your shared PCL (Portable Class Library) UI code to their corresponding native equivalent on Windows, Android and iOS. So this means that your applications are completely native! Each Xamarin Forms page is split into two parts. A XAML file to handle the Visual part of your UI and CODE BEHIND file to handle the behaviour of that page, such as buttons and displaying data.

USER INTERFACE…XAML OR C#?

Xamarin Forms provides you two options to author your application user interface.

XAML
Up first is XAML (eXtensible Application Markup Language).  This is an ideal method for front-end designers to get their feet wet with mobile UI development.  If you have any experience or knowledge of using XML, HTML, CSS etc. to create UI’s you will find familiarity using this markup especially with the aid of Visual Studios helpful intellisense.  Great news for any existing .NET developer used to developing desktop apps using WPF or Silverlight, you will be able to hit the ground running with little to no learning curve with more or less the same XAML markup you’re used to. Below is an example of a simple UI created using XAML.  As you can see all the elements are enclosed in HTML like tags and within each of these tags you have properties that you can set values with. For example if we take the “button” tag from the example below you will see a tag with a few properties and values such as “Text”, “TextColor”, “BackgroundColor”, any web designer with some experience of HTML and CSS will see the similarities in the markup and be able to get comfortable with XAML very quickly.

<?xml version="1.0" encoding="UTF-8"?>
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MyApp.MainPage">
<TabbedPage.Children>
<ContentPage Title="Profile" Icon="Profile.png">
<StackLayout Spacing="20" Padding="20" VerticalOptions="Center">
<Entry Placeholder="Username" Text="{Binding Username}"/>
<Entry Placeholder="Password" Text="{Binding Password}" IsPassword="true"/>
<Button Text="Login" TextColor="White" BackgroundColor="#77D065" Command="{Binding LoginCommand}"/></StackLayout>
</ContentPage>
<ContentPage Title="Settings" Icon="Settings.png">
<!-- Settings -->
</ContentPage>
</TabbedPage.Children>
</TabbedPage>

C#
The second option is to create your UI in code. If you are a web developer, who knows C# or another object orientated programming language, or maybe are a web developer more used to backend programming then this may be the option you decide to take to create your mobile app user interface. For designers not used to programming markup the syntax may seem rather strange, but the takeaway here is BOTH the XAML markup above and the C# code below produce the exact same UI.

using Xamarin.Forms;
var profilePage = new ContentPage {
Title = "Profile",
Icon = "Profile.png",
Content = new StackLayout {
Spacing = 20, Padding = 50,
VerticalOptions = LayoutOptions.Center,
Children = {
new Entry { Placeholder = "Username" },
new Entry { Placeholder = "Password", IsPassword = true },
new Button {
Text = "Login",
TextColor = Color.White,
BackgroundColor = Color.FromHex("77D065") }}}};
var settingsPage = new ContentPage {
Title = "Settings",
Icon = "Settings.png",(...)};
var mainPage = new TabbedPage { Children = { profilePage, settingsPage } };

The image below shows the UI we have created from the mark up in XAML and C# and how it looks across the three platforms iOS, Android and Windows.

SO…WHICH IS BEST FOR UI?
From my experience coming from a front-end design background before becoming a full stack .NET developer I would say I certainly found creating the UI with XAML the preferred method as it gave you a hierarchical structure somewhat similar to HTML web pages I had created in the past. Once you learn the controls, layouts and associated properties it was very straightforward to take the design concepts you know from responsive web design and apply it to a native mobile app interface. Again, what UI option you take is purely down to what your current skill set is and what you are most comfortable with learning, however, for newcomers to Xamarin Forms I feel XAML would be your best option. So for the rest of this article all of the UI examples I’m going to show you will be using XAML mark-up.

PAGES, LAYOUTS & CONTROLS

Like most modern websites mobile apps have similar user interfaces and page elements. Xamarin Forms kindly provides you with a good set of pages, layouts and controls out of the box to get you started developing mobile apps.


PAGES

There is five main pages types you can build your UI with, these are ContentPage, MasterDetailPage, NavigationPage, TabbedPage and finally CarouselPage. Here’s a brief explanation of each type, for more detailed descriptions on the different page types here is a link to Microsoft Docs.
https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/controls/pages

CONTENT PAGE
This is the simplest page type in Xamarin Forms, the ContentPage can only contain one element. In the example below we have a content page with a single button element. In real world applications there is very few pages with just one element, so generally content pages will have a single layout container which you can then add many control elements to the layout.

MASTERDETAIL PAGE
Any designer with experience creating mobile responsive websites will find this page type familiar. This page type essentially has two parts a “Master” and a “Detail”.  The Master page is generally a layout which includes a hamburger style menu with a list of pages you can navigate to.  Upon selecting one of the pages from the menu the layout then displays the Detail page which is the content for that page selected.

NAVIGATION PAGE
Navigation pages are used to provide a navigation experience through your app for both navigating forwards and backwards. Navigation pages uses a stack format which means as you navigate either forward the current page will be pushed below the stack and the new page promoted to the top of the stack and likewise for going backwards the current page is popped back and previous page pushed to the top of the stack. This type of page is often used for web style forms for data entry. In the example below we see a signup page after the user has logged into the app, but notice in the top left corner you see a backwards arrow button. This shows the user that they can navigate backwards to the previous page.

TABBED PAGE
Like tabs on websites, the TabbedPage gives you the ability to have several pages displayed in a tab menu format. This type of page type is often seen in News apps to separate types of articles or sections.  If you take a look at the Twitter app on your mobile phone you will see an example of a TabbedPage with a set of icons separating the tabs.

CAROUSEL PAGE
Like the name of this page suggests, it’s a page type that allows you to have a collection of children pages or objects which can be navigated to using finger swipe gestures. This page type is often used for gallery style apps for collections of images / videos. A good example of this type of page in use would be photo gallery apps like Instagram.

LAYOUTS

Now you know the page types available for you to fill with content, you need to know how to display that content using layouts. Again Xamarin Forms offers a generous set of layouts to suit pretty much any type of app you wish to develop. These layouts are StackLayout, AbsoluteLayout, RelativeLayout, GridLayout, ContentView, ScrollView and finally Frame. In this article I am going to highlight the main three that you will be more likely use whilst getting started creating mobile apps with Xamarin Forms.

STACKLAYOUT
The StackLayout is probably the most used layout you will use when creating your user interfaces in Xamarin Forms. A StackLayout allows you to display multiple elements in a single line either horizontally or vertically by default.  You can also create more complex user interfaces by using a StackLayout as a base layout then nesting other StackLayout or other layouts within it. You can see in the example below there is a base StackLayout with five child elements, two labels, 2 Entry Cells and finally a button. See how all the child elements are arranged in a vertical stack format. Below is the markup in XAML which produces this example.


<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="LoginNavigation.LoginPage"
Title="Login">
<ContentPage.ToolbarItems>
<ToolbarItem Text="Sign Up" Clicked="OnSignUpButtonClicked" />
</ContentPage.ToolbarItems>
<ContentPage.Content>
<StackLayout VerticalOptions="StartAndExpand">
<Label Text="Username" />
<Entry x:Name="usernameEntry" Placeholder="username" />
<Label Text="Password" />
<Entry x:Name="passwordEntry" IsPassword="true" />
<Button Text="Login" Clicked="OnLoginButtonClicked" />
<Label x:Name="messageLabel" />
</StackLayout>
</ContentPage.Content>
</ContentPage>

ABSOLUTE LAYOUT
When you are looking for more control over the elements in your UI such as positioning and sizing on your screen then this is the layout for you. Good examples of an AbsoluteLayout in use would be the login page of an app. For example let’s take a look at Jaguar’s mobile app, you can see there is the Jaguar logo positioned in the centre at the top of the screen and then a set of buttons and labels positioned at the bottom of the screen.

GRID LAYOUT
The last layout I want to cover here is the GridLayout. The GridLayout is used to arrange your UI elements in rows and columns. The main thing here is not to confuse this layout with HTML tables, and expect the ability to use it to display web style table data. The GridLayout is solely intended to be used for laying out your elements. Good examples of a GridLayout being used would be Windows 10 Metro style tile interface, a telephone keypad or in the example below a calculator app interface.

Once you get more comfortable with using layouts in Xamarin Forms you will see the unlimited potential in combining and nesting layouts for awesome user interfaces.  For more detailed explanations of layouts and best practices for them check out the link below from Microsoft.
https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/layouts/

CONTROLS

Anyone who has used Microsoft’s Visual Studio IDE will be familiar with a toolbox full of pre-set controls that you can use to build your user interface and in Xamarin Forms you have out the box around 30 controls you can use right away. Again like most website designs as you find your way with Xamarin Forms you will mostly use a smaller set of these controls given how similar mobile app user interfaces are.

Below we’re going to go through some of the main controls you will use in Xamarin Forms and quite quickly you’ll begin to notice in the controls you can set properties of the control elements which can be used position, change appearance or create an event when a control is used.  If you’re coming from a web design background you will find these properties which you can set familiar. In the early days of web design the look and display of elements were driven mostly from inline properties in the mark-up but now almost all websites use CSS to handle the control properties and their respective values. The good news here is Xamarin Forms adopts a similar standard in that you can set the values in the inline mark-up like you will see in the controls below, or you can set style rules in the apps Resource Dictionary in the App.xaml file. We will discuss the Resource Dictionary later in this article but for now we can look at the set of controls you will mostly use when creating mobile apps for the first time.

LABEL
Like a label on a website this control is used for displaying text. Normally a label is used above elements like a login form textbox to instruct the user what they should be entering in that control.

<Label Text="Username:" HorizontalOptions="CenterAndExpand"
FontAttributes="Bold" Margin="0,0,0,5" ></Label>


DATEPICKER
Datepickers are used in UI’s to capture maybe someone’s Date of Birth or in calendar style apps to select a date to create an entry. In the mark-up below you will see a property “x:name”, this property is used to give your control an ID which you can reference in the code behind file to carry out more dynamic tasks.

<DatePicker x:Name="phDOB" Date="{Binding Path=DateTimeNow}"
HorizontalOptions="EndAndExpand"></DatePicker>


PICKER
The picker control is the mobile app equivalent of a dropdown list from the web. Like websites this can either have hardcoded values or can be data driven. You can see you declare the Picker control and then there is a sub tag Picker.Items, this is where you add the values you wish to be displayed in the Picker. In my example I’m display a list of strings, this can be a list of whatever datatype you wish to display.

<Picker x:Name="PaymentTypes" Title="Select Your Payment Method">
<Picker.Items>
<x:String>Credit Card</x:String>
<x:String>Debit Card</x:String>
<x:String>Cash</x:String>
</Picker.Items>
</Picker>


PROGRESS BAR
An ideal visual indicator control to show users progress who may be using an app where they are filling out a form which has multiple pages. You will see a new property in the mark-up below HeightRequest, this value is set to display the thickness of the progressbar line. You manage the progressbar “Progress” value by setting this in the code behind file using the X:Name reference of the progressbar control. The value you can set is a decimal between 0 and 1, this specifies the fraction of the bar that is colored. So for example to set the value, you would declare the value by adding the following to your code behind file, ApplicationProgress.Progress = 0.2f.


<ProgressBar x:Name="ApplicationProgress" HeightRequest="5"></ProgressBar>

SLIDER
This control should not be confused of Slider carousels of images you often see on websites. This control is often used for settings pages such as the brightness indicator on your smartphones screen. Notice 2 properties in the mark-up Minimum and Maximum. You can set these to your desired values, by default if you don’t set these properties then the minimum starts at 0 and Maximum is 1.


<Slider x:Name="slider" Minimum="0" Maximum="10" />

LISTVIEW
The ListView is one of the most used UI controls in mobile app design. Its primary function is to display lists of data that normally require scrolling. Examples of a ListView in mobile apps would be your contacts list in your phone, text messages list, Twitter or Facebook feeds, maybe even a products page.  In real world mobile apps ListViews are generally populated with dynamic data from a database or maybe a remote webservice. In the mark-up below you see how we declare a ListView and then we have a sub tag ListView.ItemTemplate, in this tag we can set how we want the list to be displayed and the also the data in the ListView. How we set the data we do this in the DataTemplate tag. The ListView has two built in DataTemplates for you to use, TextCell and ImageCell. In this example we are using the TextCell. The TextCell template has two properties Text and Detail, in the screenshot below this is a simple event app and you see the Text property shows the Location of the event and the Detail below the Text shows the Date of the event. ListViews are extremely important in a good UI for a mobile app, so you should take time to learn all the aspects of the ListView control.


<ListView x:Name="eventsListView" ItemSelected="eventsListView_ItemSelected" HasUnevenRows="True"><ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding Location}" Detail="{Binding Date}" /
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

ACTIVITY INDICATOR
The ActivityIndicator control is often used to show the user that something is happening in the mobile app. A good example would be if a user has entered a Postcode in a form and clicked on a button to find the full address, it may take a few seconds to return the data so this is a good control to use to show the user the app is working on something and has not just crashed. The look and style of the activity indicator will vary on the target platform of the app.

<ActivityIndicator IsRunning="true" IsVisible="True" Color ="White"/>

 

ENTRY
This control is basically what web designers refer to as a textbox. A simple element to enter text. Often used in a form. In the mark-up below you see several properties you can set in the Entry control. Two in particular to pay attention to is Placeholder, which you can set placeholder text in the Entry control to give the user some indication of what should be entered. The second is Keyboard, this is an excellent property in which you can specify which type of keyboard on the device you wish to display when the user is entering text, such as if a user was entering a telephone number to a form you could select “Telephone” and this will force the device to display a number keyboard very much like you telephone keypad when making calls. By using the keyboard property correctly this makes your UI more intuitive to the user to use.

<Entry x:Name="txtUser" Margin="0,0,0,10" BackgroundColor="White" Placeholder="Username" FontSize="Small" TextColor="#a41f35" Keyboard="Default"></Entry>

BUTTON
The Button control is another control web designers will be very familiar with. The Button control is primarily used to fire an event when the Button is pressed. In the mark-up below you can set many properties to style the button and text but the one property to pay particular attention to is “Clicked”. This is the click event fired when you click the button, you handle what you want to do when the button is clicked in the code behind file for the page. An example of a button click would be on a login page after the user has entered their username and password the event would then navigate the user to a welcome screen or dashboard.

<Button Text="Login" BackgroundColor="#a41f35" FontAttributes="Bold" TextColor="White" Clicked="LoginButton_Clicked" HeightRequest="50"/>

For more in-depth details on all the controls available in Xamarin Forms and also some advance uses please check out this link from Microsoft.
https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/controls/views

STYLES

In order to cut down on the repetition of writing the same XAML mark-up to style your UI elements Xamarin Forms provides you the method to set styles explicitly in the App.xaml page in a tag called ResourceDictionary. This is a similar concept to CSS for web design. You can set styles for specific controls and can have those styles applied to controls in your UI by using a reference property called X:Key. In the example below you will see I have set styles for a Button control and created a X:Key reference called PrimaryButton.


<ResourceDictionary>
<Style x:Key="PrimaryButton" TargetType="Button">
<Setter Property="BackgroundColor" Value="Red"/>
<Setter Property="TextColor" Value="#FFFFFF"/>
<Setter Property="BorderRadius" Value="20"/>
<Setter Property="FontAttributes" Value="Bold"/>
</Style
</ResourceDictionary>

Now to use this style I have set in the Resource Dictionary, in my XAML page I declare a button and to apply the styling I use the “Style” property and provide the value PrimaryButton. You will see I prefix this value with a keyword StaticResource, this is to tell Xamarin Forms that the style elements for this control is a static resource in the App.xaml page.

<Button Text=”Login” Style=”{StaticResource PrimaryButton}”/>

By using the ResourceDictionary to store your Style elements your XAML mark-up becomes cleaner and less verbose. The additional benefit is if you eve decided to change your apps theme as part of an update you only have the one place to change the properties rather than having to go through all your apps pages and change them individually.

EXTENDING XAMARIN FORMS

Extending the default functionality of your Xamarin Forms app couldn’t be easier. Visual Studio comes pre-packaged with its own plugin and extension library repository, NUGET PACKAGE MANAGER. This allows you to download and install essential libraries, third party tools and plugins from developers all around the world that can help cut down your development time and simplify your app.

Here is a list of popular plugins compiled by the Xamarin community. You will see this is an extensive list of
https://github.com/xamarin/XamarinComponents

Here is a few packages I want to highlight that you should consider installing as part of any app you create. Using these libraries will enable you to create a dynamic mobile app with an attached database and have the ability to send and receive data from external web service sources.

NEWTONSOFT.JSON
A popular JSON framework for Serializing and Deserializing strings and objects. This is a secure way to transmit data to and from web services.
https://components.xamarin.com/view/json.net

MICROSOFT.NET.HTTP
This is an essential package when you need to work with HTTP / REST web service endpoints to write and read data.

SQLITE-NET-PCL
SQLite-net is an open source and light weight library providing easy SQLite database storage for Xamarin forms applications. On most good websites the content displayed must always be fresh and up to date in order to keep users interested and in mobile apps this even more important.  In web design to make your content dynamic it would generally involve connecting to a SQL Server or Oracle Instance to send and receive data. In general mobile apps are designed to be lightweight and using such databases and structures would potentially cause your app to perform poorly. So what’s the answer…SQLite!  Luckily SQLite bridges the gap when dealing with data and is the go to database for mobile application development. SQLite is a lightweight relational database that is installed on the user’s device as part of the app install. This allows you to have a dynamic application where you can store data in the SQLite database for populating Picker controls, ListViews etc. You can perform CRUD (Create, Read, Update, and Delete) operations with SQLite.
https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/databases

SO WHATS NEXT?

You will agree from what I have covered here Xamarin Forms is a very powerful platform for designers and developers to create cross platform mobile apps. This is only a taste of what you can potentially create with Xamarin Forms and whether you are an existing mobile application developer developing apps for iOS / Android or maybe a web designer / developer investigating how to get into mobile app development I recommend you take a look at Xamarin Forms. The ability to create one code base and build your app for all platforms not only save you time and money but also gives you the ability to provide your customer / businesses app accessibility across all platforms and devices. For anyone looking for more information using Xamarin Forms or more guidance on mobile application development you can contact Eric McDonald at Arca Studios.

Start Your Own Freelance Business!

Learn how I went from a corporate employee to owning my own freelance business and blog. Sign up for my email newsletter and get a FREE copy of my Ebook plus a coupon for 10% off your first billing cycle on any Vandelay Premier plan!

Looking for hosting? WPEngine offers secure managed WordPress hosting. You’ll get expert WordPress support, automatic backups, and caching for fast page loads.