Xamarin.Forms ListView

1. 创建项目

启动 Visual Studio,新建一个空白的 Xamarin.Forms 应用,项目名称为:

ListViewTutorial

2. 创建基本界面

双击打开 MainPage.xaml,删除所有模板代码,替换为以下内容:

<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="ListViewTutorial.MainPage">
    <StackLayout Margin="20,35,20,20">
        <ListView>
            <ListView.ItemsSource>
                <x:Array Type="{x:Type x:String}">
                    <x:String>Baboon</x:String>
                    <x:String>Capuchin Monkey</x:String>
                    <x:String>Blue Monkey</x:String>
                    <x:String>Squirrel Monkey</x:String>
                    <x:String>Golden Lion Tamarin</x:String>
                    <x:String>Howler Monkey</x:String>
                    <x:String>Japanese Macaque</x:String>
                </x:Array>
            </ListView.ItemsSource>
        </ListView>
    </StackLayout>
</ContentPage>Code language: HTML, XML (xml)

说明

  • 界面由一个 StackLayout 和一个 ListView 组成。
  • ListView.ItemsSource 属性用于指定要显示的数据源。
  • 上述代码通过 XAML 直接为 ListView 填充了一个字符串数组。

3. 填充数据

3.1 使用代码隐藏为 ListView 填充数据

在实际开发中,通常使用代码隐藏中定义的集合(实现 IEnumerable 接口)为 ListView 填充数据。

添加 Monkey 类

解决方案资源管理器中,右键点击 ListViewTutorial 项目,添加名为 Monkey 的类,代码如下:

public class Monkey
{
    public string Name { get; set; }
    public string Location { get; set; }
    public string ImageUrl { get; set; }

    public override string ToString()
    {
        return Name;
    }
}Code language: JavaScript (javascript)

3.2 在代码隐藏中初始化数据

双击打开 MainPage.xaml.cs,删除所有模板代码,替换为以下代码:

using System.Collections.Generic;
using Xamarin.Forms;

namespace ListViewTutorial
{
    public partial class MainPage : ContentPage
    {
        public IList<Monkey> Monkeys { get; private set; }

        public MainPage()
        {
            InitializeComponent();

            Monkeys = new List<Monkey>();
            Monkeys.Add(new Monkey
            {
                Name = "Baboon",
                Location = "Africa & Asia",
                ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/f/fc/Papio_anubis_%28Serengeti%2C_2009%29.jpg/200px-Papio_anubis_%28Serengeti%2C_2009%29.jpg"
            });

            Monkeys.Add(new Monkey
            {
                Name = "Capuchin Monkey",
                Location = "Central & South America",
                ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/4/40/Capuchin_Costa_Rica.jpg/200px-Capuchin_Costa_Rica.jpg"
            });

            Monkeys.Add(new Monkey
            {
                Name = "Blue Monkey",
                Location = "Central and East Africa",
                ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/BlueMonkey.jpg/220px-BlueMonkey.jpg"
            });

            Monkeys.Add(new Monkey
            {
                Name = "Squirrel Monkey",
                Location = "Central & South America",
                ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/2/20/Saimiri_sciureus-1_Luc_Viatour.jpg/220px-Saimiri_sciureus-1_Luc_Viatour.jpg"
            });

            Monkeys.Add(new Monkey
            {
                Name = "Golden Lion Tamarin",
                Location = "Brazil",
                ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/8/87/Golden_lion_tamarin_portrait3.jpg/220px-Golden_lion_tamarin_portrait3.jpg"
            });

            Monkeys.Add(new Monkey
            {
                Name = "Howler Monkey",
                Location = "South America",
                ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/0/0d/Alouatta_guariba.jpg/200px-Alouatta_guariba.jpg"
            });

            Monkeys.Add(new Monkey
            {
                Name = "Japanese Macaque",
                Location = "Japan",
                ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c1/Macaca_fuscata_fuscata1.jpg/220px-Macaca_fuscata_fuscata1.jpg"
            });

            Monkeys.Add(new Monkey
            {
                Name = "Mandrill",
                Location = "Southern Cameroon, Gabon, Equatorial Guinea, and Congo",
                ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/7/75/Mandrill_at_san_francisco_zoo.jpg/220px-Mandrill_at_san_francisco_zoo.jpg"
            });

            Monkeys.Add(new Monkey
            {
                Name = "Proboscis Monkey",
                Location = "Borneo",
                ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e5/Proboscis_Monkey_in_Borneo.jpg/250px-Proboscis_Monkey_in_Borneo.jpg"
            });

            Monkeys.Add(new Monkey
            {
                Name = "Red-shanked Douc",
                Location = "Vietnam, Laos",
                ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/9/9f/Portrait_of_a_Douc.jpg/159px-Portrait_of_a_Douc.jpg"
            });

            Monkeys.Add(new Monkey
            {
                Name = "Gray-shanked Douc",
                Location = "Vietnam",
                ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/0/0b/Cuc.Phuong.Primate.Rehab.center.jpg/320px-Cuc.Phuong.Primate.Rehab.center.jpg"
            });

            Monkeys.Add(new Monkey
            {
                Name = "Golden Snub-nosed Monkey",
                Location = "China",
                ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c8/Golden_Snub-nosed_Monkeys%2C_Qinling_Mountains_-_China.jpg/165px-Golden_Snub-nosed_Monkeys%2C_Qinling_Mountains_-_China.jpg"
            });

            Monkeys.Add(new Monkey
            {
                Name = "Black Snub-nosed Monkey",
                Location = "China",
                ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/5/59/RhinopitecusBieti.jpg/320px-RhinopitecusBieti.jpg"
            });

            Monkeys.Add(new Monkey
            {
                Name = "Tonkin Snub-nosed Monkey",
                Location = "Vietnam",
                ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/9/9c/Tonkin_snub-nosed_monkeys_%28Rhinopithecus_avunculus%29.jpg/320px-Tonkin_snub-nosed_monkeys_%28Rhinopithecus_avunculus%29.jpg"
            });

            Monkeys.Add(new Monkey
            {
                Name = "Thomas's Langur",
                Location = "Indonesia",
                ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/3/31/Thomas%27s_langur_Presbytis_thomasi.jpg/142px-Thomas%27s_langur_Presbytis_thomasi.jpg"
            });

            Monkeys.Add(new Monkey
            {
                Name = "Purple-faced Langur",
                Location = "Sri Lanka",
                ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/0/02/Semnopithèque_blanchâtre_mâle.JPG/192px-Semnopithèque_blanchâtre_mâle.JPG"
            });

            Monkeys.Add(new Monkey
            {
                Name = "Gelada",
                Location = "Ethiopia",
                ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/1/13/Gelada-Pavian.jpg/320px-Gelada-Pavian.jpg"
            });

            BindingContext = this;
        }
    }
}Code language: PHP (php)

说明

  • 定义了 IList<Monkey> 类型的 Monkeys 属性。
  • 在构造函数中初始化 Monkeys 集合,并添加多个 Monkey 对象。
  • 将页面的 BindingContext 设置为 MainPage 对象本身,以便进行数据绑定。

3.3 绑定 ItemsSource

MainPage.xaml 中,修改 ListView 声明,将 ItemsSource 属性绑定到 Monkeys 集合:

<ListView ItemsSource="{Binding Monkeys}" />Code language: HTML, XML (xml)

4. 响应项选择

4.1 在 XAML 中绑定事件

修改 MainPage.xaml 中的 ListView 声明,为 ItemSelectedItemTapped 事件设置处理程序:

<ListView ItemsSource="{Binding Monkeys}"
          ItemSelected="OnListViewItemSelected"
          ItemTapped="OnListViewItemTapped" />Code language: HTML, XML (xml)

4.2 在后台代码中实现事件处理程序

MainPage.xaml.cs 中添加以下事件处理方法:

void OnListViewItemSelected(object sender, SelectedItemChangedEventArgs e)
{
    Monkey selectedItem = e.SelectedItem as Monkey;
}

void OnListViewItemTapped(object sender, ItemTappedEventArgs e)
{
    Monkey tappedItem = e.Item as Monkey;
}Code language: JavaScript (javascript)
事件说明
事件说明
ItemSelected当选择新项时触发。点击同一项两次,只会触发一次该事件
ItemTapped当点击某项时触发。点击同一项两次,会触发两次该事件
  • sender 参数为触发事件的 ListView 对象。
  • SelectedItemChangedEventArgs 提供所选中的项。
  • ItemTappedEventArgs 提供被点击的项。

5. 自定义单元格外观

5.1 使用 DataTemplate 和 ViewCell

MainPage.xaml 中,修改 ListView 声明以自定义每行的外观:

<ListView ItemsSource="{Binding Monkeys}"
          HasUnevenRows="true"
          ItemSelected="OnListViewItemSelected"
          ItemTapped="OnListViewItemTapped">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <Grid Padding="10">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto" />
                        <RowDefinition Height="*" />
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto" />
                        <ColumnDefinition Width="*" />
                    </Grid.ColumnDefinitions>
                    <Image Grid.RowSpan="2"
                           Source="{Binding ImageUrl}"
                           Aspect="AspectFill"
                           HeightRequest="60"
                           WidthRequest="60" />
                    <Label Grid.Column="1"
                           Text="{Binding Name}"
                           FontAttributes="Bold" />
                    <Label Grid.Row="1"
                           Grid.Column="1"
                           Text="{Binding Location}"
                           VerticalOptions="End" />
                </Grid>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>Code language: HTML, XML (xml)

说明

  • ListView.ItemTemplate 属性设置为 DataTemplate,用于定义每行数据的外观。
  • DataTemplate 的子级必须属于或派生自 Cell 类型。
  • 使用 ViewCell 创建自定义布局,内部通过 Grid 管理 Image 和两个 Label 的排列。
  • 数据绑定:
    • Image.Source 绑定到 Monkey.ImageUrl
    • Label.Text 分别绑定到 Monkey.NameMonkey.Location
  • ListView.HasUnevenRows="true" 允许各行根据内容自动调整高度,适用于长度可变的文本。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注