2020.09.01.

Xamarin.Forms Binding in C#

By bence960206

What is Binding actually?

For example, we have an application and it’s communicate with a database. So it’s store and query data from the db. And if it display a List (and the List depends on the user’s data [name,age]) and it don’t know what should it display. So we make a database query and we give it to a List and it will display it. But how? Via Binding.

Binding is responsible for a list of which item should contain the user’s name and age and what kind of collection should be the input with the user’s information.

What will we need?

We need a class, which contains the user’s information.

public class User{

public string name{get;set;}

public int age {get;set;}

}

We need a collection such as ObservableCollection or just a simple List, which contains the users, which we will display.

ObservableCollection<User> users = new ObservableCollection<User>();

User user = new User();

user.name = ”John”;

user.age = 20;

users.Add(user);

Ok, then we need a DataTemplate, a ViewCell, a Grid and a ListView.

DataTemplate: Specifying the appearance of data.

ViewCell: A Cell containing a developer-define View.

Grid: supports arranging views into rows and columns.

ListView: the data displays as a List.

var personDataTemplate = new DataTemplate(() =>

{

var grid = new Grid();

var nameLabel = new Label { TextColor = Color.Black, FontAttributes = FontAttributes.Bold };

var ageLabel = new Label() { TextColor = Color. Black};

nameLabel.SetBinding(Label.TextProperty, “name”);

whereLabel.SetBinding(Label.TextProperty, “age”);

grid.Children.Add(nameLabel, 0, 0); //first 0: from the left(column) //and the second from up(row)

grid.Children.Add(whereLabel, 1, 0);

viewCell = new ViewCell

{

View = grid,

};

return viewCell;

});

lw = new ListView()

{

ItemsSource = users,

ItemTemplate = personDataTemplate

};