Group ListView by a component on a JSON in Xamarin.Forms

前端 未结 1 1419
孤街浪徒
孤街浪徒 2021-01-17 05:25

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.

相关标签:
1条回答
  • 2021-01-17 06:13

    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>
    
    0 讨论(0)
提交回复
热议问题