Xamarin Listview分组 [英] Xamarin Listview grouping
问题描述
我正在处理xamarin.froms中的列表视图.我可以轻松地为每个记录填充一个listite的listview:
I am dealing with a listview in xamarin.froms. I can easily populate the listview with a listitem for each record:
[
{"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来自此json源的列表视图中的项
//9 Items in listview from this json source
但是我想要将所有项归为某个键值,在这里说"cat"
并实现以下目标:
But what I want is to group all the items on some key value, say "cat"
here and achieve something like this:
任何对此的建议或方法,将不胜感激.
Any suggestion or approach toward this would be appreciated.
推荐答案
将数据分组到集合中,然后将这些集合添加到ListView中.集合必须是您自己的类,并且具有用于将组与之绑定的属性.
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.
这是一个演练:
在ListView上设置分组,包括将每个组绑定到的属性,在本例中为"GroupKey"
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;
像以前一样将单元绑定到MyDataClass:
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;
查看有关为何使用模板K
代替Grouping
类中的字符串,如何自定义标头外观的说明,以及更多:
http://motzcod.es/post/94643411707/enhancing-xamarinforms- listview-with-grouping
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
(在@pnavk的答案中提供链接的信誉)
(Credit to the link in @pnavk's answer)
这篇关于Xamarin Listview分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!