December 2015

Volume 30 Number 13

Xamarin - Build a Cross-Platform UX with Xamarin.Forms

By Keith Pijanowski

If you’ve decided to experiment with Xamarin then you’ve decided to start an exciting journey. Unlike other development tools, which tie you to a single platform, Xamarin gives you access to four different platforms. With Xamarin, you can use your C# skills to write your application for iOS, Android, Windows Phone and the Mac OS X. It’s important to note that Xamarin delivers a fully native experience. You get native performance, complete API access on all platforms and a native UI. This article will focus on the three mobile platforms supported by Xamarin: iOS, Android and Windows Phone.

The benefits of using Xamarin are exciting for many reasons. One reason is that using a platform like Xamarin is just plain fun. Xamarin is a playground to learn all these platforms in more detail while at the same time using your C# skills. Instead of having to work in multiple workspaces (Xcode, Android Studio/Eclipse and Visual Studio) with multiple languages (C#, Java and Objective-C/Swift), you can work in one familiar environment (Visual Studio) with one language (C#).

There are also a few financial advantages to developing applications with Xamarin. With Xamarin, you can create a single solution that can render a version of your application on iOS, Android, Windows Phone and OS X. Code reuse and skill set reuse between these platforms represents significant cost savings and productivity gains. When it comes to monetizing your application, basic economics dictates that increasing the number of potential customers creates more opportunity for acquiring more paying customers. Collectively, the three mobile platforms supported by Xamarin represent more than 98 percent of all mobile devices across the globe.

Finally, if you’re an enterprise building mobile line-of-business (LOB) applications, then having the ability to create a solution for all relevant platforms means that employees may use their own devices for work.

The Traditional Xamarin Approach

A Traditional Xamarin solution that supports all three mobile platforms is comprised of four projects at a minimum—a Portable Class Library (PCL) and a platform-specific project for each platform. The PCL (or a shared code project) contains the models, data access code and business logic. The code in the PCL can be referenced and reused from the other projects. However, PCLs contain no UI code. UI code is maintained in the platform-specific projects. It’s also important to note that the goal of Traditional Xamarin is to provide feature parity with the native programming environments and the platforms they represent. Everything you can do in Objective-C, Swift or Java can be done in C# with Xamarin and Visual Studio. Any API you want to access on iOS, Android and Windows Phone you can; Xamarin has 100 percent native API access. This code is also in the platform-specific projects.

While the Traditional Xamarin approach will let you share significant amounts of code, there is a way to share even more code.

Enter Xamarin.Forms

Xamarin.Forms pushes the envelope further still when it comes to reusability. Specifically, Xamarin.Forms provides all the benefits of the traditional approach while also letting UI logic be reused across platforms. Xamarin.Forms solutions are still structured the same way as Traditional Xamarin, however, the PCL can now contain UI code. The platform-specific projects are still needed for project settings and to house images and other resources that are different across platforms.

It’s no surprise the folks at Xamarin would attempt to do this. Even though iOS, Android and Windows Phone were conceived by different architects and grew up under different roofs, there is still a lot of commonality within their UIs. Users view content one page at a time. Also, many controls are similar across platforms. For example, text boxes, push buttons, radio buttons, labels, list views and image controls are relatively the same across platforms. In total, Xamarin.Forms comes with 40 controls, seven layouts and five page types for building native UXes.

The programming model adopted by Xamarin.Forms is XAML/­C#. Pages, layouts and controls can be specified using XAML in much the same manner as pages created in a Windows Phone project. Pages, layouts and controls may also be created entirely in code. Both techniques will be shown in this article.

When using Xamarin.Forms what can be tricky is designing and implementing the UI that organizes your application’s features and content. This has to be done in a way that maximizes code reuse while at the same time producing an application that is natural to use on each platform. To this end, Xamarin provides five page types to address common UI scenarios: Content pages for displaying basic content; Navigation pages for providing navigational features; Tabbed pages for creating pages that have tabs across the top or bottom of the screen; Master-Detail pages for presenting high-level data and detail data across two panes of information; and Carousel pages for creating pages that scroll content horizontally. This article will demonstrate the Xamarin.Forms solution to each of these scenarios by discussing each of the five page types. Page layouts and UI controls that come with Xamarin.Forms will also be shown along the way.

Displaying Content

Displaying basic content on a screen is done with the Content page. Figure 1 shows the XAML for a page that’s used to capture user feedback.

Figure 1 XAML for a Content Page

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
  xmlns:x="http://schemas.microsoft.com/winfx/2009/XAML"
  x:Class="XamarinFormsTestHarness.FeedbackPage"
  Title="Feedback">
  <StackLayout Padding="10,10,10,10">
<Label Text="Name:" FontAttributes="None" FontSize="Medium" TextColor="#3498DB"/>
  <Entry Text="{Binding Name}" Placeholder="First and Last" Keyboard="Default"/>
  <Label Text="Email:" FontSize="Medium" TextColor="#3498DB" />
  <Entry Text="{Binding Email}" Placeholder="name@company.com" Keyboard="Email" />
  <Label Text="Feedback:" TextColor="#3498DB" FontSize="Medium"/>
  <Editor Text="{Binding Text}" HeightRequest="200" BackgroundColor="Gray"/>
    <Button x:Name="ButtonSubmitFeedback" Text="Submit"
      BackgroundColor="#3498DB"
      TextColor="White"
      Command="{Binding SaveFeedbackCommand}"/>
  </StackLayout>
</ContentPage>

The XAML in Figure 1 uses a stack layout to organize basic controls such as Label, Entry, Editor and Button. As an example of Xamarin.Forms native capabilities, on iOS an Entry is rendered as a UITextField, on Android as an EditText and on Windows Phone as a TextBox.

A note of caution: Xamarin XAML is different from Windows Phone XAML. You cannot take the XAML from a Windows Phone page and drop it into a Xamarin Content page. For example, if you are used to using the Margin and Padding properties to make subtle tweaks to the positioning of your controls, then you will be unhappy to learn that these properties are not available in many of the Xamarin.Forms controls. Additionally, many of the controls and their properties have different names as compared to their Windows Phone counterparts. These discrepancies might seem like the symptom of a new product. In many cases this might be true, but also remember that Xamarin is not just for Windows Phone developers. The goal of Xamarin is to provide an environment for mobile developers of all backgrounds. If a certain control isn’t named the same as it is in Window Phone, then chances are that the name Xamarin is using is a name that comes from either Android or iOS.

The Content page is the building block for all the other page types. Carousel pages, Tabbed pages, Navigation pages and Master Detail pages use content pages to build their UXes.

Master Detail Scenarios

Master Detail Scenarios are very common in mobile applications. Therefore, Xamarin built a specific page type to handle this scenario. A Master Detail page can be used to organize application functionality or application data. For example, in an application that manages customers and orders, a list of customers can be shown in a Master page. Once the user touches a specific customer, then all the orders for that customer can be shown in a details page. A Master Detail page can also be used to show the menu options of an application. In this scenario, the Master page displays a list of features available within the application and each detail page provides the appropriate feature. Figure 2 shows the constructor code for a Master Detail page used as the main menu of a fitness application. Figure 3 shows how the Master page is rendered on each platform. A Master page is rendered on iOS and Android as a popover menu that slides in from the left side of the screen. On Windows Phone it’s rendered as a complete page. When users touch an option, they’re taken to the appropriate page.

Figure 2 Code for the Master Detail Page

using System;
using Xamarin.Forms;
namespace XamarinFormsTestHarness
{
  public class MasterDetailControlPage : MasterDetailPage
  {
    public MasterDetailControlPage()
      {
      MenuPage menuPage = new MenuPage();
      menuPage.MenuListView.ItemSelected += (sender, e) =>
        MenuSelected(e.SelectedItem as MenuItem);
      // The Detail page must be set or the page will crash when rendered.
      this.Master = menuPage;
      this.Detail = new NavigationPage(new FeedbackPage());
      this.IsPresented = true;
      }
        ...
  }
}

Master Detail Page Rendered on iOS (Left), Android (Center) and Windows Phone (Right)
Figure 3 Master Detail Page Rendered on iOS (Left), Android (Center) and Windows Phone (Right)

There are quite a few facts worth noting about the code in Figure 2 to make it understandable. First, the Master Detail page is really a controller. It does not contain the UX of the Master page or any of the Detail pages. These pages are in separate files. Its job is to show the correct page based on the user’s request. In Figure 3 the Master page is a content page named MenuPage. MenuPage is instanti­ated and set into the Master property of the Master Detail page. The XAML for MenuPage isn’t shown here for brevity. It can be found in the code download that accompanies this article. The Master Detail page shown in Figure 2 also does not contain the UX for any of the Detail pages. They are also in separate files. The Detail pages are instantiated and set into the Detail property of the Master Detail page when the user selects a menu option.

In the constructor of the Master Detail page both the Master page and the Detail page are set. The Master Detail page will bomb out when initially shown if  both properties are not set.

It’s also important to understand the IsPresented property. This property indicates whether the Master page is shown to the user. If it is set to True then the Master page is shown. If it is set to False then the current Detail page is shown.

Windows Phone treats the entire Master page experience as a single page view. In other words, when the user navigates to a detail view Windows Phone doesn’t treat it as standard-page navigation. When the user taps the back button on a detail view, the user will be taken to the page shown prior to the initial navigation to the Master Detail page. This is a poor UX as the user was most likely expecting to be taken back to the Master view of the Master Detail page. To get around this problem Xamarin.Forms lets the OnBackButtonPressed event to be overridden. This event is invoked on both Windows Phone and Android because all Windows Phone and Android devices have a back button. This event is not invoked if your app is running on iOS as iOS does not have a back button. On iOS the user can navigate back to the master page by tapping the master page’s icon, which will be displayed in the upper left of all detail pages. It’s important to always set the Master page’s icon property, otherwise the user will be trapped on one of the application’s detail pages with no way to get back to the Master page.

Application Navigation

The Navigation page manages page navigation for iOS and Android. NavigationPages are push/pop navigation. Push a new page to the top of the stack and then pop it off. The Windows Phone OS keeps track of all navigation and all Windows Phone devices have a hardware back key. Therefore, the user can always go back to the previous screen. So, on Windows Phone the Navigation page has no effect.

For iOS and Android the Navigation page provides a UX that shows the title of the current page and the title of the previous page as a link at the top of the page. The root page will only contain the title of the page. If users touch the title of the previous page they’re taken back to the previous page.

The easiest way to use the Navigation page is to instantiate it in code and pass a page into its constructor. The following line of code is used to create the detail pages in Figure 2:

this.Detail = new NavigationPage(displayPage);

Navigation pages are especially important on iOS because the devices on which it runs don’t have a hardware back button. Without the features provided by the Navigation page, users would not have the ability to go back one page on iOS.

Tabs

The UI of a tabbed page is rendered as a list of tabs that appear either at the top of the screen or at the bottom. On iOS, the list of tabs appears at the bottom of the screen, and the detail area is above. If there are more tabs than can fit on the screen, then the iOS rendering will provide a “More” tab that provides access to the options that could not fit on the screen. On Android the tabs appear across the top of the screen with the detail area below. The user can horizontally scroll the collection of tabs if the collection is too large to fit on the screen. On Windows Phone the tabbed page is rendered as a Pivot page.

There are two ways to create a tabbed page. First, application developers can set Content Page objects into the tabbed page’s Children property, as shown in Figure 4. One tab will be created for each entry into the Children collection. The Title and Icon properties of each page are used to create the tabs. This technique is useful when each tab will have a different look and feel and the data in each tab is different. Figure 5 shows how the tabbed page from Figure 4 is rendered on each platform.

Figure 4 Creating a Tabbed Page with the Children Property

using Xamarin.Forms;
namespace XamarinFormsTestHarness
{
  class TabbedControlPage : TabbedPage
    {
    public TabbedControlPage()
      {
      this.Title = "My Workouts";
      this.Children.Add(new ThisWeek());
      this.Children.Add(new LastWeek());
      this.Children.Add(new ThisMonth());
      this.Children.Add(new LastMonth());
      this.Children.Add(new All());
      }
    }
}

The Tabbed Page Rendered on iOS (Left), Android (Center) and Windows Phone (Right)
Figure 5 The Tabbed Page Rendered on iOS (Left), Android (Center) and Windows Phone (Right)

Another way to create a tabbed page is to assign a list of objects instantiated from the same class to the tabbed page’s ItemsSource property. One tab will be created for each object in this list. A DataTemplate must then be set into the tabbed page’s ItemTemplate property. The DataTemplate must be created from a Content page that uses data binding to get data from the corresponding object in the ItemSource property. It’s important to bind this Content page’s title property to a property in the bound object. The Title property will be used to create the tab label. The remainder of this content page may be used to bind to other properties from the bound object. This technique is best for tabbed pages where each tab will have the same UX showing different data.

Carousels

The UI of a Carousel page lets the user swipe the screen from side to side in order to show different pages of content. Windows Phone developers will recognize the Carousel page as a Panorama. The Carousel page contains a Children property just like the tabbed page. To create a Carousel page, set Content page objects into the Children property of the Carousel page. Each Content page will be rendered as a screen of content. The Title property of each Content page isn’t used in Carousel pages. (This is different from tabbed pages where each Title is used as the tab title.) Therefore, if you need a label for each screen, then you’ll need to implement this manually as part of the Content page content. Figure 6 shows how this page is rendered on each platform. Notice that on iOS and Android there’s no visible clue informing the user of additional content to the left or right of the current view. Windows Phone does this by showing a portion of the page title. For this reason, be careful using a Carousel on iOS and Android. Users might miss important content in your application.

Carousel Page Rendered on iOS (Left), Android (Center) and Windows Phone (Right)
Figure 6 Carousel Page Rendered on iOS (Left), Android (Center) and Windows Phone (Right)

Designing for Three Platforms

If you’re familiar with all three platforms then at this point you’ve probably realized that each of the Xamarin.Forms page types represents a UI scenario that’s needed in one of the platforms and it was then creatively implemented in the other two. For example, Navigation pages that provide a link to the previous page are needed to provide back-key functionality on iOS because iOS doesn’t have a back key. Navigation pages are also rendered on Android in a similar fashion because having a link to the previously visited page at the top of the current page is a popular UI structure on Android even though Android has a back key.

Similarly, Tabs are used quite often on both iOS and Android. Therefore, Xamarin.Forms needed to have this UI structure in the toolbox. On Windows Phone tabs are rendered as Pivot pages, which are an essential part of the OS.

Master Detail pages provide a popover panel, which is sometimes used on iOS and Android.

Finally, Windows Phone has the concept of a Panorama page. Panorama pages are best used as the homepage of an application. The idea of a Panorama page is to provide a high-level view of the application. A well-designed Panorama page is like a magazine cover. It gives the user a quick glimpse at what’s inside. If done in a compelling manner, the Panorama pulls the user further into the application. The idea of horizontally swiping between screens of content isn’t a familiar scenario in iOS and Android. Therefore, care must be taken when using a Carousel page in a Xamarin.Forms application.

As the Xamarin.Forms platform evolves, more page types will most likely be added. A Xamarin developer will have a design responsibility to look at each page type and determine if it makes sense for all the platforms his app is targeting.

Wrapping Up

Xamarin presents two main approaches to building native applications that share code: Traditional Xamarin and Xamarin.Forms. Picking the right approach depends on what you’re building.

Use the Traditional Xamarin approach when your application needs specialized interactions on each platform and makes use of many platform-specific APIs. Traditional Xamarin also provides the power to build UIs that are customized for each platform.

Xamarin.Forms is a complete framework for building native appli­cations using a single, shared code base. Consider Xamarin.Forms if you’re prototyping, building a data entry application or your application requires little platform-specific functionality. Xamarin.Forms is also good for projects where sharing code is more important than a custom UI for each platform.


Keith Pijanowski is an engineer, entrepreneur and businessman. He has more than 20 years of experience in the software industry and has worked for startups and large companies in roles that range from writing code to business development. Reach him at keithpij@msn.com or on Twitter: @keithpij.

Thanks to the following technical expert for reviewing this article: Pierce Boggan (Xamarin)