我正在处理 xamarin.froms 中的 ListView 。我可以轻松地用每条记录的列表项填充 ListView :
[
{"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"}
]
//来自这个 json 源的 listview 中的 9 个项目
但我想要的是根据某个键值对所有项目进行分组,在这里说 "cat"
并实现如下目标:
对此有任何建议或方法,我们将不胜感激。
最佳答案
将您的数据分组到集合中,并将这些集合添加到您的 ListView 中。集合需要是您自己的类,具有用于绑定(bind)组的属性。
这是一个演练:
在您的 ListView 上设置分组,包括将每个组绑定(bind)到的属性,在本例中为“GroupKey”
myListView.IsGroupingEnabled = true;
myListView.GroupDisplayBinding = new Binding("GroupKey"); // See below
然后将您的数据分组(例如列表列表)。这通常意味着您需要创建自己的类来显示您的分组,例如:
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);
}
}
最后,分组添加数据:
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)到 MyDataClass:
var cell = new DataTemplate(typeof(TextCell));
cell.SetBinding(TextCell.TextProperty, "SomePropertyFromMyDataClass");
cell.SetBinding(TextCell.DetailProperty, "OtherPropertyFromMyDataClass");
myListView.ItemTemplate = cell;
查看它以了解为什么在 Grouping
类中使用模板 K
而不是字符串,如何自定义标题外观等等:
http://motzcod.es/post/94643411707/enhancing-xamarinforms-listview-with-grouping
(归功于@pnavk 回答中的链接)
关于android - Xamarin Listview 分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31845171/