Group your data into collections and add those collections into your ListView. The collections need to be your own class with a property for binding the group with.
Here's a walkthrough:
Set up grouping on your ListView including a property to bind each group to, in this case "GroupKey"
myListView.IsGroupingEnabled = true;
myListView.GroupDisplayBinding = new Binding("GroupKey"); // See below
And then add your data in groups (e.g. lists of lists). This often means you need to create your own class to show your groupings, such as:
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);
}
}
And finally, add your data in 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 the MyDataClass as you would have before:
var cell = new DataTemplate(typeof(TextCell));
cell.SetBinding(TextCell.TextProperty, "SomePropertyFromMyDataClass");
cell.SetBinding(TextCell.DetailProperty, "OtherPropertyFromMyDataClass");
myListView.ItemTemplate = cell;
Check it out for explanation on why to use template K
instead of a string in the Grouping
class, how to customise the header look, and much more:
http://motzcod.es/post/94643411707/enhancing-xamarinforms-listview-with-grouping
(Credit to the link in @pnavk's answer)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…