Search code examples
listviewmauigroup

Maui group a List<T> and show it in a ListView


I have a list with this structure:

public class Words
{
    public string Word { get; set; }
    public int Word_Order { get; set; }
    public string Type { get; set; }
    public string Mainmeaning { get; set; }
    public string Language { get; set; }
    public string Meaning_Group { get; set; }
    public string Source { get; set; }
    public string Translation { get; set; }
    public string IPAUK { get; set; }
    public string IPAUS { get; set; }
    public string WordForms { get; set; }
    public string Level { get; set; }
    public string Examples { get; set; }
}

Each Words.Word can repite n times. I'd like to meke a new List grouped by the by each Word and show it in a ListView where in the main line shows (Word,IPAUK,IPAUS) and for each word shows Type, Mainmeaning and Translation.

Thanks in advance.


Solution

  • I recommend to use CollectionView instead of ListView. They are similar with some differences: CollectionView and ListView differences. However,There is a known issue about iOS GroupHeaderTemplate :ListView GroupHeaderTemplate produces blank headers on iOS and MacCatalyst. It just render a blank headers.That's why i recommend to use CollectionView.

    In your case, I suppose that you want the Words.Word to be the Group title name. So you could follow the documentation: Display grouped data in a CollectionView.

    First step is to create a type that models a single item. (Is this model Words class?)

    Then there should be a WordsGroup class which inherits from the List class.

    public class WordsGroup : List<Words>
    {
        public string Name { get; set; } // this is the group title name
    
    
        public WordsGroup(string name, List<Words> words) : base(words)
        {
            Name = name;
        }
    }
    

    Also there is an IEnumerable collection of group which ItemSources of Collection should bind to.

    public List<WordsGroup> WordsGroups { get; private set; } = new List<WordsGroup>();
    

    Then we could add group data in many ways. Actually, I don't know how you organize your data. So I cannot give you specific suggestions. Maybe you may refer to my previous post

    Also in CollectionView don't forget to set IsGrouped to true.

    <CollectionView ItemsSource="{Binding WordsGroups}" 
          IsGrouped="True">
    

    Hope it works for you.