Xamarin Listview Grouping

I am dealing with a list in xamarin.froms. I can easily populate a combo box for each entry:

[ {"cat":1, "name":"alpha"}, {"cat":1, "name":"beta"}, {"cat":1, "name":"gamma"}, {"cat":2, "name":"john"}, {"cat":2, "name":"william"}, {"cat":2, "name":"smith"}, {"cat":2, "name":"steve"}, {"cat":3, "name":"abc"}, {"cat":3, "name":"xyz"} ] 

// 9 Items in the list from this json source

enter image description here

But I want to group all the elements with some key value, say "cat" here and achieve something like this:

ListView with grouping

Any suggestion or approach to this will be appreciated.

+4
source share
3 answers

You need to enable grouping as follows:

  myListView.IsGroupingEnabled = true; myListView.GroupDisplayBinding = new Binding("GroupKey"); // See below 

Then add your data to groups (for example, lists of lists). This often means that you need to create your own class to show your groups, for example:

  public class Grouping<K, T> : ObservableCollection<T> { // NB: This is the GroupDisplayBinding above for displaying the header public K GroupKey { get; private set; } public Grouping(K key, IEnumerable<T> items)ac { GroupKey = key; foreach (var item in items) this.Items.Add(item); } } 

Finally, add your data to the groups:

  var groups = new ObservableCollection<Grouping<string, MyDataClass>>(); // You can just pass a set of data in (where "GroupA" is an enumerable set) groups.Add(new Grouping<string, MyDataClass>("GroupA", GroupA)); // Or filter down a set of data groups.Add(new Grouping<string, MyDataClass>("GroupB", MyItems.Where(a => a.SomeFilter()))); myListView.ItemSource = groups; 

Bind your cell to MyDataClass, as before:

  var cell = new DataTemplate(typeof(TextCell)); cell.SetBinding(TextCell.TextProperty, "SomePropertyFromMyDataClass"); cell.SetBinding(TextCell.DetailProperty, "OtherPropertyFromMyDataClass"); myListView.ItemTemplate = cell; 

Credit for the link in @pnavk's answer.
Check out the explanation for using the K template instead of a string in the Grouping class, how to customize the appearance of the header, and more:
http://motzcod.es/post/94643411707/enhancing-xamarinforms-listview-with-grouping

+2
source

Grouping items is really straightforward with Xamarin formats. This blog post shows you how to tweak the code so you can create a grouped ListView: http://motzcod.es/post/94643411707/enhancing-xamarinforms-listview-with-grouping

+4
source

Xamarin.Forms ListView supports grouping. Check out their documentation http://developer.xamarin.com/guides/cross-platform/xamarin-forms/user-interface/listview/customizing-list-appearance/#Grouping to find out how to use it.

0
source

All Articles