Again, the MainPage is just a NavigationPage containing a custom content page defined below.
public App()
{
MainPage = new NavigationPage(new FruitListPage());
}
The content of the FruitListPage is a ListView. It has three important properties as well as an event handler for recognizing tap gestures:
- ItemsSource connects the ListView to a List which contains the items to be displayed. In this example it is a list of the custom class Fruit defined below.
- ItemTemplate defines how each item is displayed. Apposite to the Fruit items we will define a corresponding FruitCell.
- RowHeight is the height of each row. In order to encapsulate the complete layout definition into the FruitCell class, we define the RowHeight there and use it here.
- ItemTapped is the event of tapping a list item. The event handler is a delegate which deselects the currently selected item and pushes a new FruitDetailPage, which we will define below as well.
{
public FruitListPage()
{
var listView = new ListView {
ItemsSource = new List<Fruit> {
new Fruit { Name = "Apple", Description = "Awesome!" },
new Fruit { Name = "Banana", Description = "Beautiful!" },
new Fruit { Name = "Cherry", Description = "Cheap!" },
},
ItemTemplate = new DataTemplate(typeof(FruitCell)),
RowHeight = FruitCell.RowHeight,
};
listView.ItemTapped += (sender, e) => {
listView.SelectedItem = null;
Navigation.PushAsync(new FruitDetailPage(e.Item as Fruit));
};
Title = "Fruits";
Content = listView;
}
}The Fruit class only consists of two strings, a name and a description:
public class Fruit
{
public string Name { get; set; }
public string Description { get; set; }
}
The visual representation of a Fruit, the FruitCell, contains two labels arranged in a StackLayout. Their Text properties are bound to the corresponding Fruit properties. Note that we don’t need to specify a binding context, since it is automatically set to the Fruit instance associated with the current cell.
public class FruitCell: ViewCell
{
public const int RowHeight = 55;
public FruitCell()
{
var nameLabel = new Label { FontAttributes = FontAttributes.Bold };
nameLabel.SetBinding(Label.TextProperty, "Name");
var descriptionLabel = new Label { TextColor = Color.Gray };
descriptionLabel.SetBinding(Label.TextProperty, "Description");
View = new StackLayout {
Spacing = 2,
Padding = 5,
Children = {
nameLabel,
descriptionLabel,
},
};
}
}Last but not least we define a page that is opened when tapping on a list item. Its Title is set to the Nameof the current fruit. The Description is shown as a Label centered on the page.
public class FruitDetailPage: ContentPage
{
public FruitDetailPage(Fruit fruit)
{
Title = fruit.Name;
Content = new Label {
Text = fruit.Description,
HorizontalOptions = LayoutOptions.CenterAndExpand,
VerticalOptions = LayoutOptions.CenterAndExpand,
};
}
}