Choosing quickly from a long list of items is one of the key offerings of the mobile UI. The limited real estate on mobile phone screens makes data grids a challenge and leads to extensive and creative use of lists. Grouping of items, scrolling, gesture-sensitivity, and images make lists one of the most versatile and reuseable data-bound tools available. Lists are to mobile development what the data grid is to web development.
Binding ListView to a data model is made easy in Xamarin.Forms through the use of ListView’s built-in adapter called ItemTemplate. Prepare your data model class and assign it to the ListView.ItemsSource property. Then bind each property of your model to the list using the ItemTemplate.SetBinding method.
Create a data model, or custom class, containing the list items. Call it ListItem.
public class ListItem {
public string Title { get; set; }
public string Description { get; set; }
}
Populate it and point the ListView’s ItemsSource property to it.
listView.ItemsSource = new ListItem [] {
new ListItem {Title = "First", Description="1st item"},
new ListItem {Title = "Second", Description="2nd item"},
new ListItem {Title = "Third", Description="3rd item"}
};
Format list rows using ItemTemplate. Create a DataTemplate class and pass in the cell type to display. The standard cell type is TextCell, which will display a title for each row plus some detail text which you’ll add in a minute. Specify the property to display as the main row text by assigning it to the TextProperty of the list, in this case Title.
listView.ItemTemplate = new DataTemplate (typeof(TextCell));
listView.ItemTemplate.SetBinding(TextCell.TextProperty, "Title");
This will display the same list but from custom class ListItem instead of a List of Strings. No additional adapter needed!
Add a descriptive line of text to each row by binding the DetailProperty of the TextCell.
listView.ItemTemplate.SetBinding(TextCell.DetailProperty, "Description");
This binds the Description property of the ListItem class to the DetailProperty of the TextCell.
TextCell’s font color can be set using its TextColor property and the detail font color can be set using the DetailColor property.
var template = new DataTemplate (typeof(TextCell));
template.SetValue(TextCell.TextColorProperty, Color.Red);
template.SetValue (TextCell.DetailColorProperty, Color.Blue);
listView.ItemTemplate = template;
When handling the item selection, remember to use the data model.
listView.ItemTapped += async (sender, e)
{
ListItem item = (ListItem)e.Item;
await DisplayAlert("Tapped", item.Title.ToString() + " was selected.", "OK");
((ListView)sender).SelectedItem = null;
};
That’s how to build a basic ListView bound to your data model!
See the complete example on GitHub here.