读取有关ListView的Xamarin文档,您可以在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,但是仍然很好奇它是否可以完成?
您可以定义ListView.items并将其他一些WPF控件放入其中。
<ListView>
<ListView.Items>
<Label Content="123"/>
<TextBox Text="ABC"/>
<CheckBox Checked="True"/>
</ListView.Items>
</ListView>
您可以通过将列表项放入某种观察力的列表中来定义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"
xmlns:col="clr-namespace:System.Collections;assembly=mscorlib"
xmlns:models="clr-namespace:UserApp.Models"
x:Class="UserApp.Interface.SettingsPage"
Title="Settings">
<ListView>
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding DisplayName}" />
</DataTemplate>
</ListView.ItemTemplate>
<ListView.ItemsSource>
<col:ArrayList>
<models:Employee DisplayName="Rob Finnerty" />
<models:Employee DisplayName="Bill Wrestler" />
</col:ArrayList>
</ListView.ItemsSource>
</ListView>
</ContentPage>
您也可以通过从绑定中删除属性名称来使用<x:String>text</x:String>
而不是对象。