【发布时间】:2019-12-02 02:04:37
【问题描述】:
我将客户列表绑定到 Xamarin Listview。我想使用带有 ViewCell 的 DataTemplate。
根据文档,我们可以使用 2 个构造函数之一:
new DataTemplate(typeof(CustomerViewCell));
new DataTemplate(=>new CustomerViewCell);
但是,它们会导致不同的结果。第一个正确显示列表,而第二个显示重复列表的最后一项。
我不知道一些基本的东西吗?
这是我的客户模型:
public class Customers : List<Customer>
{
public Customers()
{
Add(new Customer { No = 1, Name = "Microsoft" });
Add(new Customer { No = 2, Name = "Google" });
Add(new Customer { No = 3, Name = "Facebook" });
}
}
public class Customer {
public int No { get; set; }
public string Name { get; set; }
}
这里是继承自 ViewCell 的 CustomerViewCell.xaml
<?xml version="1.0" encoding="UTF-8"?>
<ViewCell xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="LVDataTemplate.View.CustomerViewCell">
<ViewCell.View>
<StackLayout Orientation="Horizontal">
<Label Text="{Binding No}" />
<Label Text="{Binding Name}" />
</StackLayout>
</ViewCell.View>
</ViewCell>
CustomerListView,显示客户:
public partial class CustomerListView :ContentPage
{
public CustomerListView()
{
InitializeComponent();
MyListView.ItemsSource = new Customers();
//1. Work correctly
// MyListView.ItemTemplate = new DataTemplate(typeof(CustomerViewCell));
//2. Work in-correctly. only the last item repeated through out the list
var theCell = new CustomerViewCell();
MyListView.ItemTemplate = new DataTemplate(()=>theCell);
}
}
第一个代码显示结果:
- 微软。
- 谷歌
- 脸书
第二场演出
- 脸书
- 脸书
- 脸书
【问题讨论】:
-
您正在阅读哪些显示第二种格式的特定文档?
标签: xamarin.forms data-binding datatemplate