Saving Grandma’s Recipes With Xamarin.Forms — Smashing Magazine

Saving Grandma’s Recipes With Xamarin.Forms — Smashing Magazine

About The Writer

Matthew Soucoup is a Senior Cloud Developer Advocate at Microsoft spreading the love of integrating Azure with Xamarin. Matt can also be a Pluralsight writer, a …
Extra about Matthew…

When creating cellular apps, you must create and keep the consumer interface and app logic for each iOS and Android individually: Goal-C/Swift with XCode and Java with Android Studio. That may shortly flip right into a ache. With Xamarin.Forms, nevertheless, the UI and app logic on your app resides in a single codebase and also you get to make use of a single IDE to take care of all of it — saving time and complications. On this article, take a lap round Xamarin.Forms to see what it could actually do for you.

My grandma makes the most effective, most fluffiest, go weak-in-your-knees buns that anyone has ever tasted. The issue is, there’s a ton of secret components (and I’m not simply speaking love) that go into these buns, and people elements and instructions are all saved in my grandma’s head.

All of us have household recipes like that, and as an alternative of probably forgetting them, on this article we’re going to create a cellular app for iOS and Android utilizing Xamarin.Forms that may save them for myself and future generations of my household!

Drawing of buns with steam rising

Scrumptious heat buns (Giant preview)

So should you’re fascinated by writing cellular purposes, however don’t have the time to write down the identical app time and again for every platform, this text is for you! Don’t fear should you don’t know C# from a Strawberry Pretzel Salad; I’ve been writing Xamarin apps for over eight years, and this text is a tour by means of Xamarin.Forms that intends to provide you adequate info to start out studying by yourself.

What Is This Xamarin Stuff?

Greater than only a enjoyable phrase to say, Xamarin permits builders to create native iOS and Android purposes utilizing the very same SDKs and UI controls out there as in Swift and XCode for iOS or Java and Android Studio for Android.

Smashing Cat, just preparing to do some magic stuff.

Drawing of stick figure wondering if they should develop for iOS or Android

Which platform ought to I develop for? (Giant preview)

The distinction is that the apps are developed with C# utilizing the .NET Framework and Visible Studio or Visible Studio for Mac. The apps that outcome, nevertheless, are precisely the identical. They appear, really feel, and behave identical to native apps written in Goal-C, Swift, or Java.

Xamarin shines in terms of code sharing. A developer can create and tailor their UI for every platform utilizing native controls and SDKs, however then write a library of shared app logic that’s shared throughout platforms.

Drawing of stick figure with the idea to develop for both platforms at once using Xamarin

Aha! I’ll decide Xamarin! (Giant preview)

It’s this code sharing the place super time financial savings may be realized.

And just like the scrumptious buns my grandma bakes, as soon as given the style of sharing code — it’s arduous to not crave extra — and that’s the place Xamarin.Forms is available in.


Xamarin.Forms takes the idea of conventional Xamarin improvement and provides a layer of abstraction to it.

As an alternative of creating the consumer interface for iOS and Android individually, Xamarin.Forms introduces a UI toolkit that lets you write native cellular apps from a single code base.

Consider it this manner: You might have an app that wants a button. Every platform has the idea of a button. Why ought to you must write the consumer interface a bunch of various occasions when you recognize all of the consumer of your app must do is faucet a button?

That’s one of many issues Xamarin.Forms solves.

It supplies a toolkit of probably the most generally used controls and consumer interplay occasions for them, so we solely have to write down the consumer interfaces for our apps as soon as. It’s value noting although that you simply’re not restricted to the controls Xamarin.Forms supplies both — you continue to can use controls present in solely a single platform inside a Xamarin.Forms app. Additionally, we will share the appliance logic between platforms as earlier than.

The code sharing stats for apps developed with Xamarin.Forms might be off the charts. A convention organizing app has 93% of its code shared on iOS and 91% on Android. The app is open sourced. Take a peek on the code.

Xamarin.Forms offers greater than UI controls. It additionally accommodates a MVVM framework, a pub/sub messaging service, an animation API, and a dependency service, plus others.

However immediately, we’re going to concentrate on the UI capabilities for constructing our recipe supervisor app.

The App We’ll Construct

The recipe supervisor app could have an easy consumer interface. We shall be working within the kitchen, so it must be straightforward to make use of!

It should consist of three screens. The primary will present an inventory of all of the recipes at present loaded within the app.

Screenshot of the recipe list screen on iOS

(Giant preview)

Then, by tapping on a type of recipes, you’ll be capable of see its particulars on a second display:

Screenshot of the recipe detail screen on iOS

The recipe element display on iOS (Giant preview)

From there you possibly can faucet an edit button to make modifications to the recipe on the third display:

Screenshot of the recipe edit screen on iOS

The recipe edit display on iOS (Giant preview)

You may also get to this display by tapping the add button from the recipe record display.

The Improvement Setting

Xamarin apps are constructed with C# and .NET, utilizing Visible Studio on Home windows or Visible Studio for Mac on the Mac, however you want to have the iOS or Android SDKs and tooling put in, too. Getting all the things put in, within the right order might be a little bit of a problem, nevertheless, the Visible Studio installers will deal with word solely getting the IDE put in, but in addition the platform tooling.

Though a Mac is all the time required to construct iOS apps, with Xamarin you’ll be able to nonetheless develop and debug these apps from Visible Studio on Home windows! So if Home windows is your jam, there’s no want to vary your environments altogether.

Now let’s see how Xamarin.Forms will help us avoid wasting household recipes from one code base!

Recipe Listing Web page: Laying Out the UI

Let’s begin with speaking about how we’re going to format the UI for our recipe saving app!

General every display in Xamarin.Forms is comprised of three parts. A Web page. A minimum of one aspect referred to as a Format. And at the very least one Management.

The Web page

The Web page is the factor that hosts every little thing displayed on the display at one time. The Web page can also be central in navigation inside an app.

Drawing representing a Page in Xamarin.Forms

The web page (Giant preview)

We inform Xamarin.Forms which Web page to show by way of a Navigation Service. That service then will deal with displaying no matter web page in a means that’s applicable and native for the working system.

In different phrases, the code to navigate between screens has been abstracted too!

Lastly, though not the one option to do it, I code the UI of my Web page’s in XAML. (The opposite method can be to make use of C#.) XAML is a markup language that describes how a web page seems. And for now, suffice it to say, it’s kinda sorta just like HTML.

The Format

All of the controls on a web page are organized by one thing referred to as a Format.

Drawing representing some layouts in Xamarin.Forms

The layouts (Giant preview)

A number of layouts could be added to a web page.

Drawing of how the layouts interact with the page

Layouts on the web page (Giant preview)

There are a number of several types of Layouts in Types. A few of the commonest ones embrace Stack, Absolute, Relative, Grid, Scroll, and Flex layouts.

Drawing of several Xamarin.Forms layouts and how they arrange their child elements.

Widespread Xamarin.Forms layouts (Giant preview)

The Controls

Then lastly there are the controls. These are the widgets of your app that the consumer interacts with.

Drawing of a couple of Xamarin.Forms controls, each drawn as a box

A few of the controls (Giant preview)

Types include many controls that shall be used it doesn’t matter what sort of app you’re constructing. Issues like labels, buttons, entry packing containers, photographs, and naturally, record views.

When including a management to a display, you add it to a format. It’s the format that takes care of figuring the place precisely on the display the management ought to seem.

Drawing of a page holding 2 layouts, and those layouts arranging the controls according to the layout type.

All the things matches collectively! (Giant preview)

So to generate the next screens on iOS and Android respectively:

Screenshot of recipe list screen on iOS and Android

Recipe lists on iOS (left) and Android (proper) (Giant preview)

I used this XAML:

<?xml model=”1.0″ encoding=”UTF-8″?>
<ContentPage xmlns=””
<ContentPage.Content material>
<ListView x:Identify=”recipesList”>
<TextCell Textual content=”Binding Name”/>
</ContentPage.Content material>
<ToolbarItem Textual content=”Add” />

There’s a few essential issues happening right here.

The primary is the <StackLayout>. That is telling Varieties to rearrange all of the controls that comply with in a stack.

There occurs to solely be a single management within the format, and that’s a <ListView>, and we’re going to offer it a reputation so we will reference it later.

Then there’s a bit little bit of boilerplate ceremony to the ListView earlier than we get to what we’re after: the <TextCell>. That is telling Types to show easy textual content in every cell of the record.

We inform the <TextCell> the textual content we would like it to show via a way referred to as Knowledge Binding. The syntax seems like Textual content=”Binding Name”. The place Identify is a property of a Recipe class that fashions… properly, Recipes.

So how do the recipes get added to the listing?

Together with each XAML file, there’s a “code-behind” file. This code-behind permits us to do issues like deal with consumer interplay occasions, or carry out setup, or do different app logic.

There’s a perform that may be overridden in each Web page referred to as OnAppearing — which as I’m positive you guessed — will get referred to as when the Web page seems.

protected override void OnAppearing()


recipesList.ItemsSource = null;
recipesList.ItemsSource = App.AllRecipes;

Discover the recipesList.ItemsSource = AllRecipes;

That is telling the ListView — “Hey! All of your data is found in the enumerable App.AllRecipes (an application-wide variable) and you can use any of its child object’s properties to bind off of!”.

An inventory of recipes is all nicely and positive — however you’ll be able to’t bake something with out first seeing the recipe’s particulars — and we’re going to care for that subsequent.

Occasion Dealing with

With out responding to consumer touches our app is nothing greater than an inventory of scrumptious sounding recipes. They sound good, however with out understanding tips on how to prepare dinner them, it’s not of a lot use!

Let’s make every cell within the ListView reply to faucets so we will see find out how to make the recipe!

Within the RecipeListPage code-behind file, we will add occasion handlers to controls to pay attention and react to consumer interplay occasions.

Dealing with faucet occasions on the listing view then:

recipesList.ItemSelected += async (sender, eventArgs) =>

if (eventArgs.SelectedItem != null)

var detailPage = new RecipeDetailPage(eventArgs.SelectedItem as Recipe);

await Navigation.PushAsync(detailPage);

recipesList.SelectedItem = null;


There’s some neat stuff happening there.

Every time someone selects a row, ItemSelected is fired on the ListView.

Of the arguments that get handed into the handler, the eventArgs object has a SelectedItem property that occurs to be no matter is sure to the ListView from earlier than.

In our case, that’s the Recipe class. (So we don’t should seek for the thing within the grasp supply – it will get handed to us.)

Recipe Element Web page

In fact, there’s a web page that exhibits us the key elements and instructions of easy methods to make every recipe, however how does that web page get displayed?

Drawing of a stick figure dressed as a chef who is ready to start baking.

Let’s get cooking! (Giant preview)

Discover the await Navigation.PushAsync(detailPage); line from above. The Navigation object is a platform-independent object that handles web page transitions in a local style for every platform.

Now let’s take a peek on the recipe particulars web page:

Screenshot of recipe detail screen on iOS and Android

Recipe element screens on iOS (left) and Android (proper) (Giant preview)

This web page is constructed with XAML as nicely. Nevertheless, the Format used (FlexLayout) is sort of cool because it’s impressed by the CSS Flexbox.

<ContentPage.Content material>

<Picture Supply=”buns.png” FlexLayout.Foundation=”100%” />

<Label Textual content=”Binding Name” HorizontalTextAlignment=”Center” TextColor=”#01487E”
FontAttributes=”Bold” FontSize=”Large” Margin=”10, 10″ />

<BoxView FlexLayout.Foundation=”100%” HeightRequest=”0″ />

<Label Textual content=”Ingredients” FontAttributes=”Bold” FontSize=”Medium” TextColor=”#EE3F60″
Margin=”10,10″ HorizontalOptions=”FillAndExpand” />
<BoxView FlexLayout.Foundation=”100%” HeightRequest=”0″ />
<Label Textual content=”Binding Ingredients” Margin=”10,10″ FontSize=”Small” />

<BoxView FlexLayout.Foundation=”100%” HeightRequest=”0″ />

<Label Textual content=”Directions” FontAttributes=”Bold” FontSize=”Medium” TextColor=”#EE3F60″
Margin=”10,10″ HorizontalOptions=”FillAndExpand” />
<BoxView FlexLayout.Foundation=”100%” HeightRequest=”0″ />
<Label Textual content=”Binding Directions” Margin=”10,10″ FontSize=”Small” />

</ContentPage.Content material>

The FlexLayout will organize its controls in both rows or columns. The large profit comes although with the truth that it may possibly mechanically detect how a lot room there’s left on the display to put a management, and if there’s not sufficient, then it may routinely create a brand new row or column to accommodate it!

This helps drastically when coping with numerous display sizes, which there are many in cellular improvement.

Nicely, with the FlexLayout serving to us maintain the small print display wanting good, we nonetheless have to edit these recipes, proper?

You in all probability observed this:

<ToolbarItem Textual content=”Edit” Clicked=”Edit_Clicked” />

That line is chargeable for placing a button within the app’s toolbar. The Clicked=”Edit_Clicked” tells the button that when it’s clicked, look within the code behind for a perform of that identify, after which execute its code.

Which on this case, can be instantiating the Recipe Edit Web page, and pushing that onto our navigation stack utilizing the Navigation object talked about beforehand.

Recipe Edit Web page

A web page with an inventory of recipes: examine! A web page with all the small print to make the recipes: examine! All that’s now left is to create the web page that we use to enter or change a recipe whereas we watch grandma work her magic!

First, take a look at the screens:

Screenshot of recipe edit screen on iOS and Android

Recipe edit screens on iOS (left) and Android (proper) (Giant preview)

And now the code:

<ContentPage.Content material>
<RowDefinition Peak=”*” />
<RowDefinition Peak=”Auto” />
<ColumnDefinition Width=”*” />
<ColumnDefinition Width=”*” />

<TableView Grid.Row=”0″ Grid.Column=”0″ Grid.ColumnSpan=”2″
Intent=”Form” HasUnevenRows=”true”>
<TableSection Title=”General”>
<EntryCell x:Identify=”recipeNameCell” Label=”Name” />

<TableSection Title=”Ingredients”>
<StackLayout Padding=”15″>
<Editor x:Identify=”ingredientsCell” />

<TableSection Title=”Directions”>
<StackLayout Padding=”15″>
<Editor x:Identify=”directionsCell” />

<Button Textual content=”Save” Grid.Row=”1″ Grid.Column=”0″ BackgroundColor=”#EE3F60″ TextColor=”White” x:Identify=”saveButton” />
<Button Textual content=”Cancel” Grid.Row=”1″ Grid.Column=”1″ BackgroundColor=”#4CC7F2″ TextColor=”White” x:Identify=”cancelButton” />
</ContentPage.Content material>

There’s a bit extra code right here, and that’s as a result of I’m utilizing the Grid format to specify how every thing ought to lay out in a 2-Dimensional sample.

And in addition discover no knowledge binding right here. As a result of I needed to offer an instance of how one would populate the controls purely from the code behind file:

void InitializePage()

Title = TheRecipe.Identify ?? “New Recipe”;

recipeNameCell.Textual content = TheRecipe.Identify;
ingredientsCell.Textual content = TheRecipe.Components;
directionsCell.Textual content = TheRecipe.Instructions;

saveButton.Clicked += async (sender, args) =>

await CloseWindow();

cancelButton.Clicked += async (sender, args) =>

await CloseWindow();

See that TheRecipe property? It’s web page degree, holds all the info for a specific recipe, and will get set within the constructor of the web page.

Secondly, the Clicked occasion handlers for the saveButton and cancelButton are completely .NET-ified (and sure, I do make my very own phrases up very often.)

I say they’re .NET-ified as a result of the syntax to deal with that occasion just isn’t native to Java nor Goal-C. When the app runs on Android or iOS, the conduct shall be precisely like an Android Click on or an iOS TouchUpInside.

And as you’ll be able to see, every of these click on occasion handlers are invoking applicable features that both save the recipe and dismiss the web page, or solely dismiss the web page.

There it’s — we’ve got the UI down to save lots of the recipes from now till the top of time!

CSS Wha?!? Or Making The App Fairly

Saving one of the best for final: Xamarin.Forms provides us — amongst different issues — the power to type controls utilizing CSS!

The Xamarin.Forms CSS isn’t 100% what you could be used to from net improvement. Nevertheless it’s shut sufficient that anybody conversant in CSS will really feel proper at residence. Identical to me at grandma’s!

So let’s take the Recipe Particulars web page and refactor it, so it makes use of Cascading Fashion Sheets to set the visible parts as an alternative of setting all the things immediately inline within the XAML.

First step is to create the CSS doc! On this case it is going to seem like the next:

align-items: flex-start;
align-content: flex-start;
flex-wrap: wrap;

flex-basis: 100%;

flex-basis: 100%;
peak: zero;

font-size: giant;
font-weight: daring;
colour: #01487E;
margin: 10 10;

font-size: medium;
font-weight: daring;
colour: #EE3F60;
margin: 10 10;

font-size: small;
margin: 10 10;

For probably the most half, it seems to be like CSS. There are courses in there. There’s a single selector for a category sort, Picture. After which a bunch of property setters.

A few of these property setters, akin to flex-wrap or flex-basis are particular to Xamarin.Forms. Going ahead, the group will prefix these with xf- to comply with normal practices.

Subsequent up shall be to use it to XAML controls.

<StyleSheet Supply=”../Styles/RecipeDetailStyle.css” />

<ContentPage.Content material>
<FlexLayout StyleClass=”flexContent”>

<Picture Supply=”buns.png” />

<Label Textual content=”Binding Name” StyleClass=”foodHeader” />

<BoxView StyleClass=”spacer” />

<Label Textual content=”Ingredients” StyleClass=”dataLabel” HorizontalOptions=”FillAndExpand” />
<BoxView StyleClass=”spacer” />
<Label Textual content=”Binding Ingredients” StyleClass=”data” />

<BoxView StyleClass=”spacer” />

<Label Textual content=”Directions” StyleClass=”dataLabel” HorizontalOptions=”FillAndExpand” />
<BoxView StyleClass=”spacer” />
<Label Textual content=”Binding Directions” StyleClass=”data” />

</ContentPage.Content material>

Right here’s what it appeared like earlier than.

In Xamarin.Forms, to reference the CSS doc, add a <StyleSheet Supply=”YOUR DOC PATH” />. Then you’ll be able to reference the courses in every management by way of the StyleClass property.

It undoubtedly cleans up the XAML, and it makes the intention of the management clearer too. For instance, now it’s fairly apparent what these <BoxView StyleClass=”spacer” /> are as much as!

And the Picture will get itself styled all as a result of it’s an Picture and the best way we outlined the selector within the CSS.

To make certain, CSS in Xamarin.Forms isn’t as absolutely carried out as its net cousin, however it’s nonetheless fairly cool. You’ve got selectors, courses, can set properties and, in fact, that entire cascading factor happening!


Three screens, two platforms, one article, and infinite recipes saved! And you realize what else? You’ll be able to construct apps with Xamarin.Forms for greater than Android and iOS. You’ll be able to construct UWP, macOS, and even Samsung Tizen platforms!

Drawing of buns with steam rising

Scrumptious! (Giant preview)

Xamarin.Forms is a UI toolkit that permits you to create apps by writing the consumer interface as soon as and having the UI rendered natively throughout the key platforms.

It does this by offering an SDK that’s an abstraction to probably the most generally used controls throughout the platforms. Along with the UI goodness, Xamarin.Forms additionally offers a full-featured MVVM framework, a pub/sub messaging service, an animation API, and a dependency service.

Xamarin.Forms additionally provides you all the identical code advantages that conventional Xamarin improvement does. Any software logic is shared throughout all of the platforms. And also you get to develop all of your apps with a single IDE utilizing a single language — that’s fairly cool!

The place to subsequent? Obtain the supply code for this Xamarin.Forms app to offer it a spin your self. Then to study extra about Xamarin.Forms, together with the power to create an app all inside your browser, take a look at this on-line tutorial!

Smashing Editorial(dm, ra, yk, il)