Get up to 80 % extra points for free! More info:

Lesson 3 - First Cross-Platform Application in Xamarin and C# .NET

Welcome to the next lesson of the Xamarin cross-platform development course. In the previous lesson, Xamarin Project Structure and the Application Life Cycle, we showed and described the different parts of files and folders, and explained what is going on in the application from the start, through the pause, to when it's stopped. Today, we're finally going to leave the theory and write our first cross-platform Xamarin application that responds to user input.

Introduction

It has become a habit that the first application is usually "Hello World!". Even in this case, it'll be no different. Except that we won't type the greeting directly in the code. The user will write their name into a text field in the application. It'll store it into a variable and then display it in a dialog box.

Creating a New Xamarin Project

If you already have a project from the previous lessons, you can use it. If not, open Visual Studio and select New Project -> Mobile App (Xamarin.Forms). We'll name the project DialogApp.

Android Emulator Configuration

Before we start programming, we'll set up an Android emulator. In Visual Studio, we'll select Tools -> Android -> Android device manager. We'll click on "New" in the newly opened window and set the parameters we want. The default Nexus 5 X base device is enough for the start. Name the emulator profile as you like and choose the API. I have chosen the Android 9.0 API 28. We'll click on create, agree to the license terms and wait for the new components to be downloaded and installed. You can try to run the emulator.

If you encounter an error or a warning message regarding Hyper-V or Hypervisor, it's necessary to activate it in the Windows features as follows. In the Windows search, type: "Windows features" and open it. Check "Windows hypervisor platform" and apply. The computer will require a restart.

Install the Windows hypervisor Platform component - Smartphone Apps in Xamarin and C# .NET

For detailed instructions about Hypervisor issues, see the official documentation at https://docs.microsoft.com/…-for-android?…

C# DialogApp

Let's move to the Solution Explorer, where we'll open the MainPage.xaml and MainPage.xaml.cs files in the C# DialogApp section.

Shared Code Files Cross-platform Xamarin Application - Smartphone Apps in Xamarin and C# .NET

MainPage.xaml

First, let's look at the MainPage.xaml file. We know from the previous lessons that it contains the layout of our application's components. We write into it using XML with extended syntax. When creating the project, Visual Studio generated the following code:

<?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:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="DialogApp.MainPage">

    <StackLayout>
        <!-- Place new controls here -->
        <Label Text="Welcome to Xamarin.Forms!"
           HorizontalOptions="Center"
           VerticalOptions="CenterAndExpand" />
    </StackLayout>

</ContentPage>

At first glance, it's already obvious how and where to write the code. If you think it's into the <StackLayout></StackLayout> block, you're right. The default Visual Studio code does nothing but displays a welcome message in the middle of the screen: "Welcome to Xamarin.Forms!". Surely you understand that to create the classic Hello World! wouldn't give us much work :-) We'd simply rewrite the text and run the application.

Let me explain the code for beginners. The more experienced ones of you can easily skip this part. As you can see, each component is written in tags of angle brackets < .... />, similar to e.g. the HTML language. Among others, the positioning is enclosed in these too. Let's take this <Label> as an example. Basically, it's just a tag representing a text label. We set its required parameters and their values. The syntax is very simple: parameter="value". For the sake of clarity, each parameter is written on a separate line. However, it's also possible to write them in one line. Specifically for <Label>, we enter the following parameters:

  • Text - The value is the text to be displayed
  • HorizontalOptions - The horizontal position of the element
  • VerticalOptions - The vertical position of the element

You don't need to memorize these parameters nor values because Visual Studio offers us a ToolBox and a Properties window where we can simply find everything. For the more experienced, however, it's faster to write code directly. You can find the ToolBox in the left vertical bar of Visual Studio. Try to open it and look at the individual components. Next, try to click on <Label> in the code. Under the Solution Explorer, the Properties window for the selected element opened. Again, I recommend you go through the window row by row, so you have an idea how to handle the controls.

But now back to our application. We'll delete the default <Label> and write our own. Let's add the <Entry> control and the <Button> button. The code will look like this.

<StackLayout>
        <Label Text="Welcome, enter your name" />
        <Entry x:Name="name" />
        <Button x:Name="button" Text="Say hello!" />
</StackLayout>

We meet the <Entry> and <Button> controls. <Entry> is for the user input (something like a form field on a website we can type into) and <Button> is obviously a button. x: indicates the framework's model, according to which it's then constructed. It's kind of a variable equivalent. We'll take a closer look at this topic in the next lessons, where we'll cover the functions and objects of the application. So now we're finished with the XAML file and the application form is ready.

MainPage.xaml.cs

We moved to the Code Behind file MainPage.xaml.cs. Here we only meet with the C# .NET language in which we're going to handle the form we've just designed. So again, let's look at the generated structure containing the necessary using commands, namespace of our application, and the MainPage() class:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace DialogApp
{
    // Learn more about making custom code visible in the Xamarin.Forms previewer
    // by visiting https://aka.ms/xamarinforms-previewer
    [DesignTimeVisible(false)]
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        // here we're going to write our code
        }
    }
}

First, we'll save the project so that the changes made to the XAML file are reflected. Let's move to MainPage() and initialize our button under InitializeComponent();:

button.Clicked += Button_Clicked;

After typing +=, Visual Studio offers a new method to be generated for our button if you press Tab. Of course, we'll use that. Its code should look something like this:

private void Button_Clicked(object sender, EventArgs e)
{
    throw new NotImplementedException();
}

Since we want the dialog window to not block the UI thread, we'll need to use the await keyword. To be able to use it, we'll rewrite the method header to be asynchronous. Asynchronous syntax is used when we want to call an action and keep the app responding until this action is complete.

Now it's necessary to say what happens when the user presses the button. Since we want to show a dialog box with a greeting and the name typed into <Entry>, we need to start with <Entry>. We can easily delete the line with NotImplementedException() and replace it with our code:

private async void Button_Clicked(object sender, EventArgs e)
{
    string PrintName = name.Text;
    await DisplayAlert($"Hello {PrintName}!", "Welcome to the first cross-platform app.", "OK");
}

The first line tells us that the contents of the <Entry> named name are stored as a string in the PrintName variable. On the second line, we call DisplayAlert() (dialog box), where we write our variable, the greeting text and OK to close. Note that the DisplayAlert() method has 3 string parameters - "Caption", "Content", "Footer". When you hover your mouse over DisplayAlert(), Visual Studio suggests how to write the params again. Next, notice the $ sign. If we had not written it, we wouldn't have been able to insert the PrintName variable into the string simply. We write the $ before the quotation marks of the affected string.

Launching the Application

We're done, there's nothing left to do but to test our application in the emulator. In the Solution Explorer, we'll right-click the project name and select Build. When finished, roughly in the middle of the Visual Studio toolbar, we'll click the green Play-like button. The result should look something like this.

Addressing Android applications in C# .NET and Xamarin - Smartphone Apps in Xamarin and C# .NET

And after clicking on the "HELLO!" button:

Dialog in Android app in C# .NET and Xamarin - Smartphone Apps in Xamarin and C# .NET

You who has a paired iOS device can test the app on it as well. Of course, we can also run the application on the Universal Windows Platform.

I hope you like the first app and you understand everything. In the next lesson, Styling and Debugging Xamarin Apps on Android Devices, we'll focus on styling and other .NET components.


 

Previous article
Xamarin Project Structure and the Application Life Cycle
All articles in this section
Smartphone Apps in Xamarin and C# .NET
Skip article
(not recommended)
Styling and Debugging Xamarin Apps on Android Devices
Article has been written for you by Jaroslav Smrz
Avatar
User rating:
No one has rated this quite yet, be the first one!
Activities