Search code examples
.netxamlcollectionviewmaui

Master-Detail Collectionview in .Net Maui


In my collectionview on .Net Maui Im trying to have Categories, then items per category. This is trivial with viewmodel and Linq, List, or even array indexes. such as in Blazor

foreach(var cat in viewModel.Categories)
{
   <select id="@cat" [email protected](z=> z.Category == cat)>
   </select>  
}

But im having trouble doing this with CollectionView

<CollectionView x:Name="collectionViewMenuPerCategory" ItemsSource="{Binding Categories}" ItemsLayout="VerticalList" Margin="10" >
   <CollectionView.ItemTemplate>
       <DataTemplate>
            <VerticalStackLayout>
                <Label text="{Binding CategoryName}" FontSize="34">
                <CollectionView x:Name="CollectionViewPerCategory" ItemsSource="{Binding Source={RelativeSource AncestorType={x:Type local:MenuViewModel}}, Path=Menu.Items.Where(z=> z.Category == @CategoryName?}" ItemsLayout="VerticalList">
                   <!-- Each Item in sub collectionview for each category --> 
                </CollectionView>
      </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>

I have see ICollectionView filtering for WPF but dont see for Maui


Solution

  • Yes, CollectionView supports displaying grouped data, and defines the following properties that control how it will be presented:

    • IsGrouped, of type bool, indicates whether the underlying data should be displayed in groups. The default value of this property is false.
    • GroupHeaderTemplate, of type DataTemplate, the template to use for the header of each group.
    • GroupFooterTemplate, of type DataTemplate, the template to use for the footer of each group.

    These properties are backed by BindableProperty objects, which means that the properties can be targets of data bindings.

    The process for grouping data, therefore, is to:

    • Create a type that models a single item.
    • Create a type that models a single group of items.
    • Create an IEnumerable collection, where T is the type that models a single group of items. This collection is a collection of groups, which stores the grouped data. Add data to the IEnumerable collection.

    For more information, you can check document: Display grouped data in a CollectionView.