【问题标题】:How to create listview items in xaml如何在 xaml 中创建列表视图项
【发布时间】: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、自定义单元格...)。

标签: c# xaml listview


【解决方案1】:

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

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

【讨论】:

  • 它不起作用。错误:“无法分配属性项”。可能我错过了一些东西。我只是将上面的代码作为 ContentPage 子文件放置到 xaml/xml 文件中。
【解决方案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>

您还可以通过从绑定中删除属性名称来使用&lt;x:String&gt;text&lt;/x:String&gt; 代替对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多