Advanced Databinding: Part 0 – BASICS

In the ugly old days, if you had data that you wanted to display you would put the data into a variable and then write some code to copy that data to a control on your page. If the data changed, your code had to update the display. If you had a list of data, you had a bit of code to write to get each item in the list displayed in turn.

Xamarin.Forms provides Databinding to do all that work for you. Essentially you say “here’s my data and I want it in this UI element over here. If the data changes, update the display for me.” Even better you can say “here is a collection of objects, and here is how I want you to display properties from each one in turn and if something is added to or taken from the collection, adjust the list accordingly.

“Databinding” is well named: you bind your data to a control, and as the data changes, that change is reflected in the control.

Note: In all our examples we explain only the parts that are relevant to Databinding. For more on XAML, search through this site, or check out the Microsoft documentation.

Binding to a property

In the simplest case you want to bind to a single property in your code-behind. In that case, create the property

 private string _welcomeText = "Welcome to Basic DataBindings!";
 public string WelcomeText
 {
     get
     {
         return _welcomeText;
     }
     set { _welcomeText=value; }
 }

Now we’re going to add a label to the xaml page, but we’re going to tell that label to get its text from the property we just created

<Label
	FontSize="36"
	HorizontalTextAlignment="Center"
	Text="{Binding WelcomeText}"
	TextColor="White" />

That really is all there is to databinding. You mark your Xaml that you want its Text to be from the property WelcomeText in the object you’ve set as the binding context.

Binding Context

The binding context is nothing more than telling the UI where to get its data (typically a class — either the code-behind as we’ve done here, or in a View Model as you should.).

There are a couple ways to set the binding context. One is to set it directly in the constructor of the code behind, another and recently preferred approach is what we do in our example: set it in the Xaml.

<ContentPage.BindingContext>
	<model.Bookstore />
</ContentPage.BindingContext>

I’ve set the binding context to the Bookstore class in the model folder. We’ll set all that up below.

Binding Mode

Normally, your binding is from your source (the property) to the target control. But sometimes you want your data to go the other way (for example when the user is filling in a form).

<Entry Placeholder="Enter your name here..." 
		 x:Name="YourName" 
		 Text = "{Binding CustomerName, Mode=TwoWay}"/>

With two way binding the user’s entry will be put in the Property. Here I used a placeholder, but you are free to initialize the Entry with a value and then replace that value with whatever the user enters.

There actually are a number of modes, but these are the two you’ll use 90% of the time.

Collections

To show this, we need a bit of setup. I’ll create a folder named Model and in it create a class Book.

 public class Book
 {
     public string Name { get; set; }
     public string Author { get; set; }
        
 }

In the same file (because I’m lazy) I’ll create a class Bookstore, and stock it with a collection of three books.

public class BookStore
{
    public string StoreName { get; set; }
    public List<Book> Books { get; set;}
    public BookStore()
    {
        StoreName="Jesse's Books";
        var booksInStock = new List<Book>
        {
           new Book
           {
                Name="The Sound And The Fury",
                Author="Faulkner",
           },
            new Book
            {
                Name = "The Time Of Our Singing",
                Author = "Powers",
            },


            new Book
            {
                Name= "In Search of Lost Time",
                Author="Proust",

            }

        };

      Books = booksInStock;
    }
}

With that data source, we’re ready to tell Xaml how to display each one.

Template

In manufacturing you set up a template of what you want and then stamp them out one after the other. The same is true with databinding the contents of lists. We’ll set up how we want to display each book, and then feed the list to the list control and it will stamp out each item.

(Normally, I’d put the list data (the bookstore) in a ViewModel, but our focus here is on binding, not MVVM)

<ContentPage.BindingContext>
	<model:BookStore />
</ContentPage.BindingContext>

<ContentPage.Content>
	<StackLayout>
	<Label Text="Hello" />
	<Label Text="{Binding StoreName}" />
	<ListView
		ItemsSource="{Binding Books}">
		<ListView.ItemTemplate>
			<DataTemplate>
					<TextCell
					 Text="{Binding Name}" 
					 Detail="{Binding Author}"/>
			</DataTemplate>
		</ListView.ItemTemplate>
	</ListView>
</StackLayout>
</ContentPage.Content>

The first thing we see is the BindingContext being set.

Next we have our content, starting with a label that displays static text, the word Hello

Following that, we have our simple databinding as shown above, this time setting the text to whatever is in the property StoreName.

Now the fun begins. We declare a ListView element and set its ItemsSource to a list of objects; in this case the Books collection. Each member of that collection is a Book, and each Book has the properties Name and Author. These are the properties we want to display.

I think of it this way: the ListView takes one object off the collection at a time. In this case it is a Book. The template tells us which properties of that object to display.

The result is a list displaying the name and author (and because we are using a TextCell, the author is being treated as a detail.

Excelsior!

With what you’ve seen here, you are ready for the rest of our series on Advanced Data Binding. The first in that series is here.

More about databinding from Microsoft here

Source Code here

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen Pluralsight & LinkedIn Learning courses. He was a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Xamarin Certified Mobile Developer and a Xamarin MVP and a Microsoft MVP.View all posts by Jesse Liberty →

Rodrigo Juarez is a full-stack and Xamarin Certified Mobile Professional developer. His mission is to solve complex problems for his clients focusing on the results, applying the most adequate technology available and best practices to ensure a cost-effective and high-quality solution. He has 20+ years of experience in a wide variety of projects in the development of applications for web, desktop and mobile using Microsoft technologies in areas such as management, services, insurance, pharmacy and banks.  He can be reached at  Rodrigo Juarez

This entry was posted in Essentials and tagged , , . Bookmark the permalink.