android - Xamarin Listview 分组

标签 android listview xamarin cross-platform xamarin.forms

我正在处理 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 个项目

enter image description here

但我想要的是根据某个键值对所有项目进行分组,在这里说 "cat" 并实现如下目标:

ListView with grouping

对此有任何建议或方法,我们将不胜感激。

最佳答案

将您的数据分组到集合中,并将这些集合添加到您的 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/

相关文章:

javascript - 使用纯 Javascript 在 Android 上使用 mosync/phonegap 从 SD 卡读取文件

c# - 错误 "Xamarin.Android.Support.Design 27.0.2.1 is not compatible with monoandroid60"

xamarin - ListView 在 xamarin.forms 中水平和垂直滚动

c# - Xamarin 中的 MVVM 绑定(bind)

java - onStartLoading() 和forceLoad() 是在哪里调用和实现的?

android - 连接到android手机时无法读取数据库

java - 在 onListItemClick() 中启动 Activity

可点击元素的 ListView 中的 Android LongClick

android - 在 ListView 中挂起 listSelector

ios - 从多个 View 模型创建 View