【发布时间】:2020-11-09 06:31:08
【问题描述】:
对这个基本问题表示歉意,但我似乎无法在网上找到解决方案,希望您能帮助我。
第 1 步 - 我想像这样构建一个数组。
产品数组包含
- 产品名称
- 产品说明
- 产品价格
第 2 步 - 然后我想将它绑定到 ListView,这样每一行都会显示产品名称、产品描述、产品价格。
有什么想法吗?
【问题讨论】:
标签: c# xamarin mobile xamarin.forms xamarin.ios
对这个基本问题表示歉意,但我似乎无法在网上找到解决方案,希望您能帮助我。
第 1 步 - 我想像这样构建一个数组。
产品数组包含
第 2 步 - 然后我想将它绑定到 ListView,这样每一行都会显示产品名称、产品描述、产品价格。
有什么想法吗?
【问题讨论】:
标签: c# xamarin mobile xamarin.forms xamarin.ios
用ViewCell替换TextCell可以自定义单元格更多元素。
所有自定义单元格必须派生自 ViewCell,这是所有内置单元格类型使用的同一基类。
如以下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>
以下屏幕截图显示了自定义单元格的示例:
【讨论】:
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 结构。
最后,如果您需要双向数据绑定,即更新属性时,视图会自动更新,您需要在属性设置器中调用OnPropertyChanged();,如How to Implement Property Change Notification 中所述:
public string Name
{
get { return name; }
set
{
name = value;
OnPropertyChanged();
}
}
【讨论】: