如何在 xamarin 的 collectionview 中绑定嵌套列表项

How to bind nested list item in collectionview in xamarin

我是 xamarin 的新手。我越来越难以在 xamarin CollectionView 中绑定我的列表。 我从 API

得到下面的 json
{
  "OK": 200,
  "status": "success",
  "data": [
    {     
      "Category": "Category 1",
      "List": [
        {
          "SubItem": "The A1"
        },
         {
          "SubItem": "The A2"
        }
      ]
    },
    {     
      "Category": "Category 2",
      "List": [
        {
          "SubItem": "The C1 sub"
        },
         {
          "SubItem": "The C2 sub"
        }
      ]
    }
  ]
}

您的项目中应该有两个模型和一个像这样的视图模型:

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();

        BindingContext = new viewModel();
}

public class subModel
{
    public string SubItem { get; set; }
}
public class Data
{
    public string Category { get; set; }
    public IList<subModel> List { get; set; }

}

public class viewModel {

   public ObservableCollection<Data> items = new ObservableCollection<Data>();

    public viewModel() { 
        
    }

}

在xaml中绑定到一个grouped CollectionView:

<CollectionView ItemsSource="{Binding items}"
            IsGrouped="true">

    <CollectionView.ItemTemplate>
        <DataTemplate>
            <Label Text="{Binding SubItem}"/>
        </DataTemplate>
    </CollectionView.ItemTemplate>

    <CollectionView.GroupHeaderTemplate>
        <DataTemplate>
            <Label Text="{Binding Category}" />
        </DataTemplate>
    </CollectionView.GroupHeaderTemplate>
</CollectionView>