如何在 XAML 中创建 ListView 项

3

从官方的Xamarin文档中关于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,但仍然好奇是否可以实现?


1
我认为,设计(View)应该与数据访问(Model)解耦。即使是一个简单的设置页面,我建议您按照您所做的步骤进行。 - Balagurunathan Marimuthu
@BalagurunathanMarimuthu,我也喜欢将事物解耦,你说得对。但我只是好奇能否做到这一点(尽管我们正远离良好的实践)。另一件事是,TableView可以包含不同类型的单元格(例如TextCell、EntryCell、自定义单元格...)。 - broadband
2个回答

3

您可以定义ListView.Items并在其中放置一些其他的WPF控件。

<ListView>
    <ListView.Items>
        <Label Content="123"/>
        <TextBox Text="ABC"/>
        <CheckBox Checked="True"/>
    </ListView.Items>                    
</ListView>

它不起作用。错误:'无法分配属性项'。也许我错过了什么。我只是将上面的代码放置到XAML/XML文件中作为ContentPage子级。 - broadband

2

你可以通过将列表项放置在ObservableCollection中,在XAML中定义ItemSource。

<?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>代替对象。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接