这似乎是一个经典的分组列表视图用例。 James Montemagno wrote an article about this kind of need that should help you a lot.
总之,分组功能需要一个“列表列表”(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>>();
这个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="{Binding AssetsList}"
HasUnevenRows="True"
SeparatorVisibility="None"
SeparatorColor="Transparent"
IsGroupingEnabled="True">
<ListView.GroupHeaderTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<StackLayout Orientation="Horizontal">
<Label Text="AssetId"
FontAttributes="Bold"/>
<Label Text={Binding Key.AssetId}/>
</StackLayout>
<StackLayout Orientation="Horizontal">
<Label Text="Description"
FontAttributes="Bold"/>
<Label Text={Binding Key.Description}/>
</StackLayout>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.GroupHeaderTemplate>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<Label Text={Binding Description}/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>