如何在 Xamarin Forms 中将数组绑定到 ListView

How To Add Bind An Array To ListView in Xamarin Forms

很抱歉这个基本问题,但我似乎无法在网上找到解决方案,希望你能帮助我。

第 1 步 - 我想像这样构建一个数组。

产品数组包含

第 2 步 - 然后我想将它绑定到 ListView,这样每一行都会显示产品名称、产品描述、产品价格。

有什么想法吗?

ListView Data Binding 上的 Microsoft 教程中介绍了集合数据绑定。这是一个摘要,我只保留了相关部分。有关所有详细信息,请参阅教程。

首先,您的数组必须创建为 ObservableCollection,以便它在数据更改时发出事件:

ObservableCollection<Product> products= new ObservableCollection<Product>();
ProductView.ItemsSource = products;
proucts.Add(new Product { Name="Widget", Description="Wonderful", Price=2.99});

然后您需要从 XAML 中的 ListView 绑定到 ObservableCollection。为了在每一行中以您想要的方式显示数组的每个项目,您需要定义自定义 DataTemplate,如 Data Binding Basics:

中所述
<ListView x:Name="ProductView" ItemsSource="{Binding Products}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout Orientation="Horizontal" Spacing="10">

                    <Label Text="{Binding Name}" />
                    <Label Text="{Binding Description}" />
                    <Label Text="{Binding Price, StringFormat='{0:C}'}" />

                </StackLayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

注意价格绑定如何使用 StringFormat 属性 以货币格式显示价格。您可以创建自己的自定义转换器以将数据类型映射到各种对象,例如图像或颜色。如果您想为每个产品创建精美的“卡片”,您还可以使用 StackLayout 甚至创建嵌套的 StackLayout 结构。

最后,如果您需要双向数据绑定,即更新 属性 时,视图会自动更新,您需要在 [=35= 中调用 OnPropertyChanged(); ] 设置器,如 How to Implement Property Change Notification:

中所述
public string Name
{
    get { return name; }
    set
    {
        name = value;
        OnPropertyChanged();
    }
}

ViewCell 替换 TextCell 可以自定义带有更多元素的单元格。

所有自定义单元格必须派生自 ViewCell,所有内置单元格类型都使用相同的基础 class。

比如下面的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="demoListView.ImageCellPage">
    <ContentPage.Content>
        <ListView  x:Name="listView">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout BackgroundColor="#eee"
                        Orientation="Vertical">
                            <StackLayout Orientation="Horizontal">
                                <Image Source="{Binding image}" />
                                <Label Text="{Binding title}"
                                TextColor="#f35e20" />
                                <Label Text="{Binding subtitle}"
                                HorizontalOptions="EndAndExpand"
                                TextColor="#503026" />
                            </StackLayout>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </ContentPage.Content>
</ContentPage>

以下屏幕截图显示了自定义单元格的示例: