I\'m trying to group items from a JSON in the ListView.
My JSON is stored in an web repository, I already pulled it from the server and listed it but ungrouped.
Check out this article: https://xamarinhelp.com/xamarin-forms-listview-grouping/
But better to use ObservableCollection
, where the above article uses List
.
So you have to create an ObservableCollection of a type that is a subclass of ObservableCollection
.
First create a type that subclasses ObservableCollection
that will hold one group of companies by status:
public class CompanyByStatusList : ObservableCollection<Company>
{
public string Status { get; set; }
public ObservableCollection<Company> Companies => this;
}
Then create an ObservableCollection
of CompanyByStatusList
. This will be your ItemsSource for your ListView
.
public ObservableCollection<CompanyByStatusList> CompanyList { get; set; }
Then you want to create a CompanyByStatusList
for each status that holds all of the companies in that specific status, and then add each of those CompanyByStatusList
to the CompanyList
collection. Make sure to set the Status
property of each CompanyByStatusList
And make sure to set IsGroupingEnabled="true"
on your ListView
. ListView xaml:
<ListView ItemsSource="{Binding CompanyList}"
IsGroupingEnabled="true"
HasUnevenRows="true">
<ListView.GroupHeaderTemplate>
<DataTemplate>
<ViewCell>
<Label Text="{Binding Status}" />
</ViewCell>
</DataTemplate>
</ListView.GroupHeaderTemplate>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal" Margin="5" HorizontalOptions="Fill">
<Button Text="{Binding erpCode}"/>
<StackLayout HorizontalOptions="Fill">
<StackLayout Orientation="Horizontal">
<Label Text="{Binding name}"/>
<Label Text="{Binding statusReportDate}"/>
</StackLayout>
<Label Text="{Binding statusReportDescription}"/>
</StackLayout>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>