Advertisement
  1. Code
  2. Coding Fundamentals
  3. Tools

Getting Started with Xamarin.Forms: Layout Options

Scroll to top
This post is part of a series called Getting Started with Xamarin.Forms.
Getting Started with Xamarin.Forms: Basics

1. Layout Options

When it comes to designing and laying out the screens of your application, you have two main options, writing code or using XAML. If you've ever done any WPF (Windows Presentation Foundation) or Silverlight development, then you're probably already familiar with XAML. XAML is the eXtensible Application Markup Language that was created to help define an application's look and feel without having to handle it all in code. Xamarin.Forms works with both options. It will ultimately be up to you to decide which option you prefer.

It's important to note that the XAML used for Xamarin.Forms is not compatible with other forms of XAML and XAML tools.

Option 1: Using Code

If you're the type of person that loves to be in the code and wants nothing to do with any sort of markup, or a designer, then you will probably be very comfortable with this option. You programmatically instantiate different types of View objects and add them directly to a Page or to a Layout on a Page. Here's a simple example of creating a SimplePage class, instantiating a few View objects, and adding them to the Page through a StackLayout object.

1
public class SamplePage : ContentPage {
2
    public SamplePage()
3
    {
4
        Padding = new Thickness(20);
5
6
        var label = new Label
7
        {
8
            Text = "I am a simple page",
9
            BackgroundColor = Color.Blue,
10
            Font = Font.SystemFontOfSize(30),
11
            WidthRequest = 150,
12
            HeightRequest = 40
13
        };
14
15
        var button = new Button {
16
            Text = "I have a button",
17
            BackgroundColor = Color.Red,
18
            Font = Font.SystemFontOfSize( 20 ),
19
            WidthRequest = 200,
20
            HeightRequest = 200
21
        };
22
23
        var entry = new Entry {
24
            Placeholder = "I have a entry box",
25
            BackgroundColor = Color.Green,
26
            WidthRequest = 200,
27
            HeightRequest = 150
28
        };
29
30
        
31
32
        Content = new StackLayout {
33
            Spacing = 10,
34
            Children = {button, entry, label}
35
        };
36
    }
37
}

As you can see, the View objects have a number of the properties in common, which you can use to set the text, colors, spacing, height, width, etc. All you need to do now is modify the GetMainPage method in the App class to return a new instance of the SamplePage class, and away you go.

No one ever accused me of being a designer, but it's this easy to create basic pages in code.

Option 2: Using XAML

If you prefer to separate the look and feel of your application from the logic and implementation, then XAML may just be the way to go. XAML allows you to create the entire layout of your application in a specialized XML format that Xamarin can translate into the pages, layouts, views, and cells, and display them to the user. If you have never used XAML before, it may take a little getting used to. However, once you get the hang of it, it can actually be quite nice.

To use XAML in combination with Xamarin.Forms, you will need to create your project using the Blank App (Xamarin.Forms Portable) template so that all the Xamarin.Forms code can be separated into it's own dll.

In the code example of the previous section, you created a very simple ContentPage class in code. To create the very same ContentPage using XAML, right-click the PCL project and select Add > New Item. From the Add New Item dialog box, select the Forms Xaml Page template and replace the default contents with the following:

1
<?xml version="1.0" encoding="utf-8" ?>
2
<ContentPage xmlns="https://xamarin.com/schemas/2014/forms"
3
    				   xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
4
					   x:Class="SampleFormsXAMLApp.SampleXAMLPage"
5
             Padding="30">
6
  <StackLayout Spacing="10">
7
    <Label Text="I am a simple Page" 
8
           BackgroundColor="Blue" 
9
           Font="30"
10
           WidthRequest="150"
11
           HeightRequest="40"/>
12
    
13
    <Button Text="I have a button"
14
            BackgroundColor="Red"
15
            Font="20"
16
            WidthRequest="200"
17
            HeightRequest="200"/>
18
19
    <Entry Placeholder="I have a entry box"
20
           BackgroundColor="Green"
21
           WidthRequest="200"
22
           HeightRequest="150"/>
23
  </StackLayout>
24
	
25
</ContentPage>

If you run your application, you should see the same screen as in the code example. The PageLayout, and View types map to XML elements and the properties are the element attributes. You are free to use either option to create fully customizable, cross-platform user interfaces.

2. Flexibility through Data Binding

You can create apps where you create the View objects for your Page objects and explicitly set their properties, but that quickly becomes cumbersome. When you explicitly set properties in your XAML code, you're no longer able to reuse that XAML Page for anything else. In other words, you have to create new XAML pages for every variation you need. Who has time for that?

Wouldn't it be nice if you could create reusable XAML pages with no custom user interface code and keep everything logically separated? Of course. Welcome to MVVM.

4. Model-View-ViewModel

Model-View-ViewModel is an architectural pattern that was created with XAML in mind. At its core, it shares the basic concept of other architectural patterns like MVP and MVC. It was designed to separate data, the model layer, from presentation, the view layer. The conduit between the two is the ViewModel. The view model is a class that facilitates communication between the model and view layers through a mechanism known as data binding. Data binding is at the core of the MVVM pattern and is done through XAML itself. Let's take a look at an example.

5. Creating a Sample Application

Start by creating a new Xamarin.Forms application by selecting the Blank App (Xamarin.Forms Portable) project template and giving it the name of MyRecipeBox.

As you have probably guessed, this will be the foundation for a basic app that can store recipes. Let's start by creating a the basic model of the app, a recipe.

In the MyRecipeBox project, create a new folder and name it Models. This isn't a requirement, it just adds some organization to the project which always helps as it gets larger. In the Models folder, add a new class and name it Recipe. Replace the default implementation with the following:

1
public class Recipe
2
{
3
    public string Name { get; set; }
4
    public string Description { get; set; }
5
    public TimeSpan PrepTime { get; set; }
6
    public TimeSpan CookingTime { get; set; }
7
    public List<string> Directions { get; set; }
8
}

Now that you have a basic model class, you can create a view model for it. Think of a view model as a class that contains the parts of a model that need to be shown and interacted with on a screen. To keep things simple, we're going to concentrate on the top four properties.

Create a new folder in the MyRecipeBox project and name it ViewModels. In the ViewModels folder, create a new class and name it RecipeViewModel. When adopting the MVVM pattern in .NET, ViewModels are typically characterized by the fact that they implement the INotifyPropertyChanged interface. This interface is what is used to allow other parts of the code to subscribe to events and enable data binding. Replace the default implementation of the RecipeViewModel class with the following:

1
public class RecipeViewModel : INotifyPropertyChanged {
2
    private Recipe _recipe;
3
    public event PropertyChangedEventHandler PropertyChanged;
4
5
    public RecipeViewModel( Recipe recipe ) {
6
        _recipe = recipe;
7
        Directions = new ObservableCollection<string>(_recipe.Directions);
8
    }
9
    
10
    public ObservableCollection<string> Directions { get; set; }
11
12
    public string Name {
13
        get { return _recipe != null ? _recipe.Name : null; }
14
        set {
15
            if ( _recipe != null ) {
16
                _recipe.Name = value;
17
18
                if ( PropertyChanged != null ) {
19
                    PropertyChanged( this, new PropertyChangedEventArgs( "Name" ) );
20
                }
21
            }
22
        }
23
    }
24
25
    public string Description {
26
        get { return _recipe != null ? _recipe.Description : null; }
27
        set {
28
            if ( _recipe != null ) {
29
                _recipe.Description = value;
30
31
                if ( PropertyChanged != null ) {
32
                    PropertyChanged( this, new PropertyChangedEventArgs( "Description" ) );
33
                }
34
            }
35
        }
36
    }
37
38
    public string PrepTime {
39
        get { return _recipe != null ? _recipe.PrepTime.ToString() : "None"; }
40
        set {
41
            if ( _recipe != null ) {
42
                _recipe.PrepTime = TimeSpan.Parse(value);
43
44
                if ( PropertyChanged != null ) {
45
                    PropertyChanged(this, new PropertyChangedEventArgs("PrepTime"));
46
                }
47
            }
48
        }
49
    }
50
51
    public string CookingTime {
52
        get { return _recipe != null ? _recipe.CookingTime.ToString() : "None"; }
53
        set {
54
            if ( _recipe != null ) {
55
                _recipe.CookingTime = TimeSpan.Parse(value);
56
57
                if ( PropertyChanged != null ) {
58
                    PropertyChanged(this, new PropertyChangedEventArgs("CookingTime"));
59
                }
60
            }
61
        }
62
    }
63
}

You may have noticed that the RecipeViewModel implements the INotifyPropertyChanged interface. If you dig deeper into this interface, you'll see that it contains one property that needs to be implemented.

1
public interface INotifyPropertyChanged
2
{
3
event PropertyChangedEventHandler PropertyChanged;
4
}

The RecipleViewModel class takes in an instance of the Recipe class and then exposes only four of its properties. The getters associated with those properties simply return the data in the Recipe instance itself. The setters on, the other hand, check to see if PropertyChanged is not nullPropertyChanged will be null if there are no subscribers to this event. In that case, nothing happens. If PropertyChanged isn't null, then the event is called and every subscriber of the event receives the information that this view model has changed.

In the MVVM pattern, the subscriber to these events is typically the view described by the XAML allowing the user interface to update if the underlying models have changed.

It's time to create a page that shows the user the recipe data and leverages data binding to update the user interface. Start by creating a Views folder in the MyRecipeBox project. In the Views folder, add a new Forms Xaml Page and name it RecipeSummaryPage.

Replace the default XAML in the file with the following:

1
<?xml version="1.0" encoding="utf-8" ?>
2
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
3
    				   xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
4
					   x:Class="MyRecipeBox.Views.RecipeSummaryPage"
5
             Title="{Binding Name}"
6
             Padding="30">
7
  <StackLayout Spacing="10" VerticalOptions="FillAndExpand">
8
    <Label Text="Recipe Name" TextColor="Red"/>
9
    <Label Text="{Binding Name}" />
10
    <Label Text="Recipe Description" TextColor="Red"/>
11
    <Label Text="{Binding Description}"/>
12
    <Label Text="Total Prep Time" TextColor="Red"/>
13
    <Label Text="{Binding PrepTime}"/>
14
    <Label Text="Total Cook Time" TextColor="Red"/>
15
    <Label Text="{Binding CookTime}"/>
16
    <Label Text="Directions" TextColor="Red"/>
17
    <ListView ItemsSource="{Binding Directions}">
18
  </StackLayout>
19
</ContentPage>

As you can see, the binding is created by placing some formatted text where you want the bound data to appear.  The syntax to accomplish that is "{Binding xxxxx}", where xxxxx is the name of the property to which you want to bind. Finally, you may be wondering how you tie the view model you created to this view.

If you click the little arrow next to the RecipeSummaryPage.xaml file, you should see another file appear, RecipleSummaryPage.xaml.cs. This is the code behind file that contains the C# code to run this page. You need to modify the constructor of this class to look like this:

1
public RecipeSummaryPage(RecipeViewModel recipeViewModel)
2
{
3
    InitializeComponent();
4
5
    this.BindingContext = recipeViewModel;
6
}

The BindingContext property is where you need to assign the view model to create the aforementioned binding. To do that, pass an instance of your RecipeViewModel into the constructor.

To see the fruits of our labor appear on the screen, you need to make one small change to get this working. In the App.cs file, in the MyRecipeBox project, update the GetMainPage method as shown below.

1
public static Page GetMainPage() {
2
    var recipe = new Recipe {
3
        Name = "Toast",
4
        Description = "It's toast, are you kidding?",
5
        PrepTime = new TimeSpan( 0, 0, 15 ),
6
        CookingTime = new TimeSpan( 0, 2, 0 ),
7
        Directions = new List<string>{"Grab bread", "Put bread in toaster", "Eat toast"}
8
    };
9
    return new RecipeSummaryPage( new RecipeViewModel( recipe ) );
10
}

The result should look similar to the following screenshots.

In the next and final step, we'll create and display a list of Recipe objects that the user can click to bring them to a detail page. Let's start by creating a new view model that contains a list of Recipe objects. Add a new class to the ViewModels folder and name it RecipeListViewModel. Its implementation looks like this:

1
public class RecipeListViewModel
2
{
3
    public ObservableCollection<Recipe> Recipes { get; set; }
4
5
    public RecipeListViewModel(  ) {
6
        Recipes = new ObservableCollection<Recipe>();
7
8
        Recipes.Add(new Recipe {
9
            Name = "Toast",
10
            Description = "Are you kidding? It's toast.",
11
            CookingTime = new TimeSpan(0, 2, 0),
12
            PrepTime = new TimeSpan(0, 0, 15),
13
            Directions = new List<string> {
14
                "Pick up bread",
15
                "Put break in toaster",
16
                "Eat Toast"
17
            }
18
        });
19
20
        Recipes.Add(new Recipe
21
        {
22
            Name = "Cereal",
23
            Description = "You know, the breakfast stuff.",
24
            CookingTime = TimeSpan.Zero,
25
            PrepTime = new TimeSpan(0, 1, 0),
26
            Directions = new List<string> {
27
                "Put cereal in bowl",
28
                "Put milk in bowl",
29
                "Put spoon in bowl",
30
                "Put spoon in mouth"
31
            }
32
        });
33
34
        Recipes.Add(new Recipe
35
        {
36
            Name = "Sandwich",
37
            Description = "Bread and stuff.  YUM!",
38
            CookingTime = TimeSpan.Zero,
39
            PrepTime = new TimeSpan(0, 5, 0),
40
            Directions = new List<string> {
41
                "Get 2 slices of bread",
42
                "Put cheese between break slices",
43
                "Put ham between break slices",
44
                "Enjoy"
45
            }
46
        });
47
    }
48
}

You may have noticed that we hard coded the recipes in the RecipeListViewModel class. In a real application, the recipes would be fetched from a web service or a database.

Create a new page to display the list of recipes. In the Views folder, create a new Form Xaml Page and name this one RecipleListPage. Replace its contents with the following:

1
<?xml version="1.0" encoding="utf-8" ?>
2
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
3
    				   xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
4
					   x:Class="MyRecipeBox.Views.RecipeListPage"
5
             Title="Recipes">
6
  <ListView x:Name="recipeList" ItemsSource="{Binding Recipes}" ItemTapped="OnItemSelected">
7
    <ListView.ItemTemplate>
8
      <DataTemplate>
9
        <TextCell Text="{Binding Name}"/>
10
      </DataTemplate>
11
    </ListView.ItemTemplate>
12
  </ListView>
13
</ContentPage>

This XAML is quite similar to the previous example. This time, however, you only have a list view on the page. When using data binding in a ListView, you need to dig down a little deeper to do the actual binding. First, you bind the full list to the ItemsSource property of theListView and you then need to define the Template and DataTemplate of the ListView to be a TextCell and bind that TextCell to the individual property of the Recipe instance you want to display. This is what renders the recipe names onto the screen.

You can also see that there's a Name associated with the ListViewrecipeList, which will come in handy a bit later, as well as an event handler. In this case, when a user taps an item in the ListView, the ItemTapped event is fired. You have now subscribed to that event and will use a method named OnItemSelected to handle it.

In the next step, we need to do some wiring up in the RecipeListPage.xaml.cs file to set theBindingContext of our new page as well as implement the OnItemSelected event handler.

1
public partial class RecipeListPage
2
{
3
    public RecipeListPage()
4
    {
5
        InitializeComponent();
6
7
        this.BindingContext = new RecipeListViewModel( );
8
    }
9
10
    public void OnItemSelected(object sender, ItemTappedEventArgs args)
11
    {
12
        var recipe = args.Item as Recipe;
13
        if (recipe == null)
14
            return;
15
16
        Navigation.PushAsync(new RecipeSummaryPage(new RecipeViewModel(recipe)));
17
        // Reset the selected item

18
        recipeList.SelectedItem = null;
19
    }
20
}

The BindingContext property will simply be set to a new instance of the RecipleListViewModel that you created earlier. The event handler method is a little different. First, you need to check that the selected item is a recipe, which is accomplished in the following lines:

1
var recipe = args.Item as Recipe;
2
if (recipe == null)
3
    return;

If the selected item is a Recipe object, then you use the Navigation property to add a new instance of the RecipleSummaryPage to the current NavigationView. Finally, you need to make sure that no items in the list are currently selected.

1
Navigation.PushAsync(new RecipeSummaryPage(new RecipeViewModel(recipe)));
2
// Reset the selected item

3
recipeList.SelectedItem = null;

Accessing the ListView is done through the Name that was assigned to it earlier. You can get access to any View on the page by assigning a Name to theView and referring to it by name in the code.

The final change we need to make is updating the GetMainPage method in the App.cs file. as shown below:

1
public static Page GetMainPage() {
2
    return new NavigationPage(new RecipeListPage());
3
}

You return a new instance of the NavigationPage class as your main page and set its root page to a new instance of the RecipleListPage class. Now that everything is wired up, you can run your app on all three platforms and see something like the following:

Tapping one of the rows in the list takes you to the corresponding recipe summary page as you have seen before.

Conclusion

You have now seen the different options for laying out your application using Xamarin.Forms. You should feel comfortable creating basic applications that can run on the major mobile platforms using a single code base for both the business logic as well as user interface of the application. When you've spent some time working with Xamarin.Forms, the next step will be learning how to customize the application's user interface and add new controls. But that's for another day.

Next Step: Watch the Course

If you'd like to learn more about Xamarin, then check out our course Building Multi-Platform Apps With C# in Xamarin

In the course, you will learn how to create a cross-platform application from a single code base that will run on three distinctly different platforms: iOS, Android, and Windows Phone 8. Think it can’t be done? In just a little while you will be doing it yourself. Let’s get to work.

You can take the straight away with a completely free 14 day trial of a Tuts+ subscription. Take a look at our subscription options to get started or, if you're just interested in this course, you can buy it individually for $15! Here's a preview to get you started:

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.