CHAPTER 3
Xamarin.Forms is, at its core, a library that allows you to create native user interfaces from a single C# codebase by sharing code. This chapter provides the foundations for building the user interface in a Xamarin.Forms solution. Then, in the following three chapters, you will learn in more detail about layouts, controls, pages, and navigation.
The biggest benefit of Xamarin.Forms is that you can define the entire user interface of your application inside the project that you selected for sharing code, which can be (at the moment) either a PCL or a shared project. Native apps for iOS and Android you get when you build a solution will render the user interface with the proper native layouts and controls on each platform. This is possible because Xamarin.Forms maps native controls into C# classes that are then responsible for rendering the appropriate visual element, depending on the platform the app is running on. These classes actually represent visual elements such as pages, layouts, and controls.
Because the PCL or shared project can only contain code that will certainly run on all platforms, Xamarin.Forms maps only those visual elements common to all platforms. For instance, iOS and Android both provide text boxes and labels, so Xamarin.Forms can provide the Entry and Label controls that represent text boxes and labels, respectively. However, each platform renders and manages visual elements differently from one another, with different properties and behavior. This implies that controls in Xamarin.Forms expose only properties and events that are common to every platform, such as the font size and the text color.
In Chapter 8, you will learn how to use native controls directly, but for now, let’s focus on how Xamarin.Forms allows the creation of user interfaces with visual elements provided out of the box. The user interface in iOS and Android has a hierarchical structure made of pages that contain layouts that contain controls. Layouts can be considered as containers of controls that allow for dynamically arranging the user interface in different ways. Based on this paradigm, Xamarin.Forms provides a number of page types, layouts, and controls that can be rendered on each platform. When you create a Xamarin.Forms solution, whether you choose a PCL or a shared project, the project you selected for sharing code will contain a root page that you can populate with visual elements. Then you can design a more complex user interface by adding other pages and visual elements. To accomplish this, you can use both C# and the extensible Application Markup Language (XAML). Let’s discuss both ways further.
In Xamarin.Forms, you can create the user interface of an application in C# code. For instance, Code Listing 2 demonstrates how to create a page with a layout that arranges controls in a stack containing a label and a button. For now, do not focus on element names and their properties (they will be explained in the next chapter). Rather, focus on the hierarchy of visual elements that the code introduces.
Code Listing 2
var newPage = new ContentPage(); newPage.Title = "New page";
var newLayout = new StackLayout(); newLayout.Orientation = StackOrientation.Vertical; newLayout.Padding = new Thickness(10);
var newLabel = new Label(); newLabel.Text = "Welcome to Xamarin.Forms!";
var newButton = new Button(); newButton.Text = "Tap here"; newButton.Margin = new Thickness(0, 10, 0, 0);
newLayout.Children.Add(newLabel); newLayout.Children.Add(newButton);
newPage.Content = newLayout; |
Here you have full IntelliSense support. However, as you can imagine, creating a complex user interface entirely in C# can be challenging for at least the following reasons:
In the early days of Xamarin.Forms, defining the user interface could only be done in C# code. Fortunately, you now have a much more versatile way of designing the user interface with XAML, as you’ll learn in the next section. Obviously, there are still situations in which you might need to create visual elements in C#; for example, if you need to add new controls at runtime, although this is the only scenario for which I suggest you code visual elements in C#.
XAML is the acronym for eXtensible Application Markup Language. As its name implies, XAML is a markup language that you can use to write the user interface definition in a declarative fashion. XAML is not new in Xamarin.Forms, since it was first introduced more than ten years ago for Windows desktop development with Windows Presentation Foundation, and it has always been available in platforms such as Silverlight, Windows Phone, and the Universal Windows Platform.
XAML derives from XML and, among others, it offers the following benefits:
The way you define the user interface with XAML is unified across platforms, meaning that you design the user interface once and it will run on iOS, Android, and of course, Windows 10 if you work on Windows with VS 2017.
Note: XAML in Xamarin.Forms adheres to Microsoft’s XAML 2009 specifications, but its vocabulary is different from XAML in other platforms, such as WPF or UWP. If you have experience with these platforms, you will notice many differences in how visual elements and their properties are named. Microsoft is working on unifying XAML vocabularies, as you’ll learn in the section Hints for XAML Standard. Also, remember that XAML is case-sensitive for object names and their properties and members.
For example, when you create a Xamarin.Forms solution, you can find a file in the PCL project called MainPage.xaml, whose markup is represented in Code Listing 3.
Code Listing 3
<?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:App1" x:Class="App1.MainPage">
<Label Text="Welcome to Xamarin Forms!" VerticalOptions="Center" HorizontalOptions="Center" />
</ContentPage> |
A XAML file in Xamarin.Forms normally contains a page or a custom view. The root element is a ContentPage object, which represents its C# class counterpart and is rendered as an individual page. In XAML, the Content property of a page is implicit, meaning you do not need to write a ContentPage.Content element. The compiler assumes that the visual elements you enclose between the ContentPage tags are assigned to the ContentPage.Content property.
The Label element, on the other hand, represents the Label class in C#. Properties of this class are assigned with XML attributes, such as Text, VerticalOptions, and HorizontalOptions.
You probably already have the immediate perception of better organization and visual representation of the structure of the user interface. If you look at the root element, you can see a number of attributes whose definition starts with xmlns. These are referred to as XML namespaces, and are important because they make it possible to declare visual elements defined inside specific namespaces or XML schemas. For example, xmlns points to the root XAML namespace defined inside a specific XML schema and allows for adding to the UI definition all the visual elements defined by Xamarin.Forms; xmlns:x points to an XML schema that exposes built-in types; and xmlns:local points to the app’s assembly, making it possible to use objects defined in your project.
Each page or layout can only contain one visual element. In the case of the auto-generated MainPage.xaml page, you cannot add other visual elements to the page unless you organize them into a layout. For instance, if you wanted to add a button below the Label, you would need to include both the Label and the Button inside a container such as the StackLayout, as demonstrated in Code Listing 4.
Tip: IntelliSense will help you add visual elements faster by showing element names and properties as you type. You can then simply press Tab or double-click to quickly insert an element.
Code Listing 4
<?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:App1" x:Class="App1.MainPage">
<StackLayout Orientation="Vertical" Padding="10"> <Label Text="Welcome to Xamarin Forms!" VerticalOptions="Center" HorizontalOptions="Center" />
<Button x:Name="Button1" Text="Tap here!" Margin="0,10,0,0"/> </StackLayout>
</ContentPage> |
If you did not include both controls inside the layout, Visual Studio will raise an error. You can nest other layouts inside a parent layout and create complex hierarchies of visual elements. Notice the x:Name assignment for the Button. Generally speaking, with x:Name you can assign an identifier to any visual element so that you can interact with it in C# code, for example, if you need to retrieve a property value.
If you have never seen XAML before, you might wonder how you can interact with visual elements in C# at this point. In Solution Explorer, if you expand the MainPage.xaml file, you will see a nested file called MainPage.xaml.cs. This is the so-called code-behind file, and it contains all the imperative code for the current page. In this case, the simplest form of a code-behind file, the code contains the definition of the MainPage class, which inherits from ContentPage, and the page constructor, which makes an invocation to the InitializeComponent method of the base class and initializes the page. You will access the code-behind file often from Solution pad, but Visual Studio for Mac allows for another easy way that is related to a very common requirement: responding to events raised by the user interface.
Events are fundamental for the interaction between the user and the application, and controls in Xamarin.Forms raise events as normally happens in any platform. Events are handled in the C# code-behind file. Visual Studio for Mac makes it simple to create event handlers through IntelliSense. For instance, suppose you want to perform an action when the user taps the button defined in the previous code. The Button control exposes an event called Clicked that you assign the name of an event handler as follows:
<Button x:Name="Button1" Text="Tap here!" Margin="0,10,0,0"
Clicked="Button1_Clicked"/>
However, when you type Clicked=", Visual Studio offers a shortcut that allows the generation of an event handler in C# based on the event’s name, as shown in Figure 15.

Figure 15: Generating an event handler
If you press Tab, Visual Studio will insert the name of the new event handler and generate the C# event handler in the code-behind.
Tip: It is recommended that you specify an event handler name that is meaningful to the control, for example, Button1_Clicked rather than a more general name such as Handle_Clicked.
It will also automatically open the code-behind file, giving you an option to decide the location for the new event handler, as shown in Figure 16.

Figure 16: Deciding the position for the event handler
You can press arrows to move the event handler to a different location, Esc to cancel, and Enter to insert the event handler at the place where the blue line is. The event handler will look like the following:
void Handle_Clicked(object sender, System.EventArgs e)
{
throw new NotImplementedException();
}
At this point, you will be able to write the code that performs the action you want to execute. Generally speaking, event handlers’ signatures require two parameters: one of type object representing the control that raised the event, and one object of type EventArgs containing information about the event. In many cases, event handlers work with derived versions of EventArgs, but these will be highlighted when appropriate. As you can imagine, Xamarin.Forms exposes events that are commonly available on all the supported platforms.
If you look at Code Listing 3, you will see that the Orientation property of the StackLayout is of type StackOrientation, the Padding property is of type Thickness, and the Margin property assigned to the Button is also of type Thickness. However, as you can see in Code Listing 4, the same properties are assigned with values passed in the form of strings in XAML. Xamarin.Forms (and all the other XAML-based platforms) implement the so-called type converters, which automatically convert a string into the appropriate value for a number of known types. Summarizing here all the available type converters and known target types is neither possible nor necessary at this point; you simply need to remember that, in most cases, strings you assign as property values are automatically converted into the appropriate type on your behalf.
Xamarin.Forms doesn’t have a designer that allows you to draw the user interface visually with the mouse, the toolbox, and interactive windows as you are used to doing with platforms such as WPF, Windows Forms, and UWP on Visual Studio 2017. This implies that you need to write all your XAML manually. However, Visual Studio for Mac offers a nice solution represented by the Xamarin.Forms Previewer. This tool is automatically opened when you edit XAML markup, and it shows a preview of the user interface in real time as you type. Figure 17 shows the Xamarin.Forms Previewer in action. You can also disable or re-enable the previewer with the Preview button at the upper-right corner of the XAML editor window.

Figure 17: The Xamarin.Forms Previewer
Tip: Remember to rebuild your solution before opening the Xamarin.Forms Previewer for the first time.
At the bottom-right corner, the Previewer provides zoom controls. At the top, you can select the device factor (phone or tablet), the platform used to render the preview (Android or iOS), and the orientation (vertical or horizontal). If there are any errors in your XAML or if, for any reason, the Previewer is unable to render the preview, it will show a detailed error message. In the next chapters, I will often use the Previewer to demonstrate how the UI looks instead of running the emulator.
If you have experience with Windows development with WPF and UWP, you might already be used to XAML. In Xamarin.Forms, XAML follows the Microsoft XAML 2009 specifications, but its vocabulary is different from other XAML-based platforms. For example, a text box is represented by the TextBox control in WPF and UWP, but in Xamarin.Forms you have an Entry. Again, the Button control in WPF and UWP exposes an event called Click, which is instead called Clicked in Xamarin.Forms. Recently, Microsoft has announced XAML Standard, a unification of XAML dialects across platforms. XAML Standard is still in its beginning stages, so it’s not available yet. However, you can follow the progress on GitHub, and you can read an introductory blog post that explains XAML Standard’s goals in more detail.
Sharing the user interface across platforms is one of Xamarin.Forms’s main goals, and this chapter provided a high-level overview of how you define the user interface with XAML, based on a hierarchy of visual elements. You have seen how to add visual elements and how to assign their properties; you have seen how type converters allow for passing string values in XAML and how the compiler converts them into the appropriate types; and you had a first look at the Xamarin.Forms Previewer to get a real-time, integrated representation of the user interface as you edit your XAML. After this overview of how the user interface is defined in Xamarin.Forms, it is time to discuss important UI concepts in more detail, and we will start by organizing the user interface with layouts.