I am new in xamarin. I am getting difficulty to bind my List in xamarin CollectionView. I get the bellow json from API
{
"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"
}
]
}
]
}
You should have two models and a viewModel like this in your project:
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() {
}
}
In the xaml, bind to a 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>