【发布时间】:2018-02-17 00:10:34
【问题描述】:
阅读官方Xamarin documentation about listview,您在 xaml(xml 文件)中创建模板并在代码中以编程方式填充 listView 项目:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:constants="clr-
namespace:XamarinFormsSample;assembly=XamarinFormsXamlSample"
x:Class="XamarinFormsXamlSample.Views.EmployeeListPage"
Title="Employee List">
<ListView x:Name="EmployeeView">
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding DisplayName}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ContentPage>
然后你用这样的代码填写项目:
private ObservableCollection<Employee> employees = new ObservableCollection<Employee>();
public EmployeeListPage()
{
// just for demonstration purposes
employees.Add(new Employee{ DisplayName="Rob Finnerty"});
employees.Add(new Employee{ DisplayName="Bill Wrestler"});
//defined in XAML to follow
EmployeeView.ItemsSource = employees;
...
}
有没有办法在 xaml 中定义项目?我正在设置一个简单的设置页面,并想在 xml 中添加项目。我最终使用了TableView,但我仍然很好奇它是否可以做到?
【问题讨论】:
-
我相信,设计(视图)应该与数据访问(模型)解耦。我建议您按照您所做的步骤进行操作,即使它是一个简单的设置页面。
-
@BalagurunathanMarimuthu 是的,我也喜欢解耦,你说得对,但我只是好奇它是否可以完成(尽管我们正在远离好的做法)。另一件事是,TableView 可以包含不同类型的单元格(例如 TextCell、EntryCell、自定义单元格...)。