android – Xamarin Listview分组

我正在处理xamarin.froms中的listview.我可以使用listitem为每条记录轻松填充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个项目

enter image description here

但我想要的是将所有项目组合在一些关键值上,在这里说“cat”并实现如下:

ListView with grouping

任何建议或方法都将受到赞赏.

您需要启用这样的分组:

    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;

将您的单元格绑定到MyDataClass,就像之前一样:

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

相信@ pnavk的答案中的链接.
请查看解释为什么在Grouping类中使用模板K而不是字符串,如何自定义标题外观等等:
http://motzcod.es/post/94643411707/enhancing-xamarinforms-listview-with-grouping

https://stackoverflow.com/questions/31845171/xamarin-listview-grouping

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:android – Xamarin Listview分组