写过Android项目的童鞋都知道,ListView 是Android各种基本控件里面非常常用又稍稍有些难度的控件,那么在Xamarin里面究竟是怎样的呢?
首先我们来看一下ListView的定义:
An ItemsView that displays a collection of data as a vertical list.
我们可以简单的理解为一个显示数据集合的列表。那么怎样现实一个数据集合呢?我们可以用一个简单的例子说明:
using System;
using System.Collections.Generic;
using Xamarin.Forms;
namespace FormsGallery
{
class ListViewDemoPage : ContentPage
{
class Person
{
public Person(string name, DateTime birthday, Color favoriteColor)
{
this.Name = name;
this.Birthday = birthday;
this.FavoriteColor = favoriteColor;
}
public string Name { private set; get; }
public DateTime Birthday { private set; get; }
public Color FavoriteColor { private set; get; }
};
public ListViewDemoPage()
{
Label header = new Label
{
Text = "ListView",
FontSize = Device.GetNamedSize (NamedSize.Large, typeof(Label)),
HorizontalOptions = LayoutOptions.Center
};
// Define some data.
List<Person> people = new List<Person>
{
new Person("Abigail", new DateTime(1975, 1, 15), Color.Aqua),
new Person("Bob", new DateTime(1976, 2, 20), Color.Black),
// ...etc.,...
new Person("Yvonne", new DateTime(1987, 1, 10), Color.Purple),
new Person("Zachary", new DateTime(1988, 2, 5), Color.Red)
};
// Create the ListView.
ListView listView = new ListView
{
// Source of data items.
ItemsSource = people,
// Define template for displaying each item.
// (Argument of DataTemplate constructor is called for
// each item; it must return a Cell derivative.)
ItemTemplate = new DataTemplate(() =>
{
// Create views with bindings for displaying each property.
Label nameLabel = new Label();
nameLabel.SetBinding(Label.TextProperty, "Name");
Label birthdayLabel = new Label();
birthdayLabel.SetBinding(Label.TextProperty,
new Binding("Birthday", BindingMode.OneWay,
null, null, "Born {0:d}"));
BoxView boxView = new BoxView();
boxView.SetBinding(BoxView.ColorProperty, "FavoriteColor");
// Return an assembled ViewCell.
return new ViewCell
{
View = new StackLayout
{
Padding = new Thickness(0, 5),
Orientation = StackOrientation.Horizontal,
Children =
{
boxView,
new StackLayout
{
VerticalOptions = LayoutOptions.Center,
Spacing = 0,
Children =
{
nameLabel,
birthdayLabel
}
}
}
}
};
})
};
// Accomodate iPhone status bar.
this.Padding = new Thickness(10, Device.OnPlatform(20, 0, 0), 10, 5);
// Build the page.
this.Content = new StackLayout
{
Children =
{
header,
listView
}
};
}
}
}
上面代码引用自Dash的Demo,首先新建一个名称为FormsGallery的工程,在FormsGallery.cs中添加上述代码。上面的注释其实已经十分清晰明了了。效果如下: