看起来像是一个典型的分组列表视图用例。 詹姆斯·蒙特马格诺写了一篇关于这种需求的文章,应该会对你有很大帮助。
总的来说,分组功能需要一个类型为“列表的列表”(IEnumerable<IEnumerable<>>
)的对象,其中每个“主项”都是一个“细节项”的列表。
为了使它更容易,您可以使用上述文章提供的类:
public class Grouping<K, T> : ObservableCollection<T>
{
public K Key { get; private set; }
public Grouping(K key, IEnumerable<T> items)
{
Key = key;
foreach (var item in items)
this.Items.Add(item);
}
}
那么,您必须将列表属性更改为以下类型:
ObservableCollection<Grouping<AssetModel, TaskDetail>> AssetsList { get; set; } =
new ObservableCollection<Grouping<AssetModel, TaskDetail>>();
< p >
这个AssetsList
是你应该绑定到ListView
的ItemsSource
属性上的。
要填充这个属性,你需要做如下操作,例如:
for (int i = 0; i < 5; i++)
{
var asset = new AssetModel();
asset.AssetId = new Guid().ToString();
asset.Description = $"Asset { i + 1} ";
asset.TaskDetailList = new List<TaskDetail>();
for (int j = 0; j < 3; j++)
asset.TaskDetailList.Add(new TaskDetail() { Description = $"Detail { (i + 1) } - { (j + 1) }" });
var group = new Grouping<AssetModel, TaskDetail>(asset, asset.TaskDetailList);
AssetsList.Add(group);
}
然后,在你的 XAML 中定义 ListView 的分组属性:
<ListView ItemsSource=""
HasUnevenRows="True"
SeparatorVisibility="None"
SeparatorColor="Transparent"
IsGroupingEnabled="True">
<ListView.GroupHeaderTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<StackLayout Orientation="Horizontal">
<Label Text="AssetId"
FontAttributes="Bold"/>
<Label Text=/>
</StackLayout>
<StackLayout Orientation="Horizontal">
<Label Text="Description"
FontAttributes="Bold"/>
<Label Text=/>
</StackLayout>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.GroupHeaderTemplate>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<Label Text=/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>