Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin Listview grouping

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 Items in listview from this json source

enter image description here

But what I want is to group all the items on some key value, say "cat" here and achieve something like this:

ListView with grouping

Any suggestion or approach toward this would be appreciated.

like image 896
Afzal Ali Avatar asked Aug 06 '15 01:08

Afzal Ali


2 Answers

In my environment, the code was not work in this url http://motzcod.es/post/94643411707/enhancing-xamarinforms-listview-with-grouping .

The code that does not work is here

var partnersSorted = from item in Partners
         orderby item.UserName
         group item by item.UserNameSort into PartnersGroup
         select new Grouping<string, Monkey>(PartnersGroup.Key, PartnersGroup);

MonkeysGrouped = new ObservableCollection<Grouping<string, Monkey>>(partnersSorted);

So I changed the code.

var sortedPartners = Partners.OrderBy(x => x.UserName).GroupBy(y => y.UserNameSort);
foreach (var item in sortedPartners)
{
     PartnersGrouped.Add(new PartnersGrouping<string, Item>(item.Key, Partners.Where(x=>x.UserNameSort == item.Key)));
}

You can see like this.

[https://i.stack.imgur.com/BswPq.png][1]

here is my all scripts

Item is Partner

Item.cs

using System;

namespace NewHeats.Models
{
    public class Item
    {
        public string Id
        {
            get;
            set;
        }
        public string UserName
        {
            get;
            set;
        }
        public DateTime RegisterDate
        {
            get;
            set;
        }
        public string Field
        {
            get;
            set;
        }
        public string Password
        {
            get;
            set;
        }
        public int Heats
        {
            get;
            set;
        }
        public string UserNameSort
        {
             get
            {
                 if (string.IsNullOrWhiteSpace(UserName) || UserName.Length == 0)
                    return "?";

                 return UserName[0].ToString().ToUpper();
            }
        }
    }
 }

PartnersGrouping.cs

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace NewHeats.Models
{
    public class PartnersGrouping<K,T> : ObservableCollection<T>
    {
        public K Key { get; private set; }

        public PartnersGrouping(K key,IEnumerable<T> items)
        {
            Key = key;
            foreach (var item in items)
            {
                this.Items.Add(item);
            }
        }
    }
}

PartnersViewModel.cs

using System;
using System.Windows.Input;
using System.ComponentModel;
using System.Collections.ObjectModel;
using Xamarin.Forms;
using NewHeats.Models;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Linq;
using System.Diagnostics.Contracts;

namespace NewHeats.ViewModels
{
    public class PartnersViewModel : BaseViewModel
    {
        public Item Me
        {
            get;
            set;
        }
        public ObservableCollection<Item> Partners { get; set; }
        public ObservableCollection<PartnersGrouping<string, Item>> PartnersGrouped { get; set; }
        public Item SelectedPartner { get; set; }
        public Command LoadPartnersCommand { get; set; }
        public PartnersViewModel()
        {
            Title = "Partners";
            Partners = new ObservableCollection<Item>();
            PartnersGrouped = new ObservableCollection<PartnersGrouping<string, Item>>();
            LoadPartnersCommand = new Command(async() =>await ExecuteLoadPartnersCommand());
        }

        async Task ExecuteLoadPartnersCommand()
        {
            Contract.Ensures(Contract.Result<Task>() != null);
            if (IsBusy)
                return;
            IsBusy = true;
            try
            {
                Me = await MockUsrDataStore.GetItemAsync("naoto");                           
                Partners.Clear();
                var allfriends = await MockFriDataStore.GetItemsAsync(true);                 
                var myFriends = allfriends.Where(x => x.MyId == Me.Id);                      
                var allUsers = await MockUsrDataStore.GetItemsAsync(true);                   

                foreach (var item in myFriends)
                {
                    var partner = allUsers.FirstOrDefault(x => x.Id == item.FriendId);       
                    if (partner!=null)
                    {
                        Partners.Add(partner);
                    }
                }
                var sortedpartners = Partners.OrderBy(x => x.UserName).GroupBy(y => y.UserNameSort);
                foreach (var item in sortedpartners)
                {
                     PartnersGrouped.Add(new PartnersGrouping<string, Item>(item.Key, Partners.Where(x=>x.UserNameSort == item.Key)));
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
            finally
            {
                IsBusy = false;
            }
        }
    }
}

PartnerPage.xaml

<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="NewHeats.Views.PartnersPage" xmlns:vm="clr-namespace:NewHeats.ViewModels" xmlns:controls="clr-namespace:ImageCircle.Forms.Plugin.Abstractions;assembly=ImageCircle.Forms.Plugin" Title="{Binding Title}">
    <ContentPage.Resources>
        <ResourceDictionary>
            <!--Page Level Resources: Compatibile with Xamarin Live Player -->
            <Color x:Key="Primary">#2196F3</Color>
            <Color x:Key="Accent">#96d1ff</Color>
            <Color x:Key="LightTextColor">#999999</Color>
        </ResourceDictionary>
    </ContentPage.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <ScrollView Grid.Row="0">
            <StackLayout Orientation="Vertical" Padding="16,40,16,40" Spacing="10">
                <ListView ItemsSource="{Binding PartnersGrouped}"
                          HasUnevenRows="true"
                          VerticalOptions="FillAndExpand"
                          IsPullToRefreshEnabled="true"
                          CachingStrategy="RecycleElement"
                          IsRefreshing="{Binding IsBusy, Mode=OneWay}"
                          RefreshCommand="{Binding LoadPartnersCommand}"
                          ItemSelected="Handle_ItemSelected"
                          SelectedItem="{Binding SelectedPartner}"
                          GroupDisplayBinding="{Binding Key}"
                          IsGroupingEnabled="true"
                          GroupShortNameBinding="{Binding Key}">
                    <ListView.GroupHeaderTemplate>
                        <DataTemplate>
                            <ViewCell Height="25">
                                <StackLayout VerticalOptions="FillAndExpand"
                                             Padding="5"
                                             BackgroundColor="#3498DB">
                                       <Label Text="{Binding Key}" TextColor="White" VerticalOptions="Center"/>
                                </StackLayout>
                            </ViewCell>
                        </DataTemplate>
                    </ListView.GroupHeaderTemplate>
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <ViewCell>
                                <Grid>
                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="60"/>
                                    </Grid.RowDefinitions>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="60"/>
                                        <ColumnDefinition Width="*"/>
                                    </Grid.ColumnDefinitions>
                                    <controls:CircleImage Source="husky.jpg"
                                                          Aspect="AspectFill"
                                                          Grid.Column="0"
                                                          Grid.Row="0"
                                                          WidthRequest="60"
                                                          HeightRequest="60">
                                    </controls:CircleImage>
                                       <StackLayout Orientation="Vertical" Grid.Column="1">
                                           <Label Text="{Binding UserName}" VerticalTextAlignment="Center"/>
                                      </StackLayout>
                                </Grid>
                            </ViewCell>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>
            </StackLayout>
        </ScrollView>
    </Grid>
</ContentPage>

Thanks!!

like image 64
Naoto Munekiyo Avatar answered Oct 16 '22 09:10

Naoto Munekiyo


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)

like image 26
noelicus Avatar answered Oct 16 '22 11:10

noelicus