Skip to main content

A-z Grouped list in LongListSelector for Windows Phone 8

This post explains how you can display data as A-z grouped list in LongListSelector control..
In this example we are going to develop a Friends List ...each friend , groped by their first letter of the name ..
final outcome would be looks like following ..



 How to develop?

First of all I wanna give you a brief explanation ...
In here initially we are going to create a List FriendsInfo) . This List contain all the details about my friends ,their names, image urls and descriptions. After we created the list we should sort this list A to Z according to their first latter of the name. for that we are using  AlphaKeyGroup class.now we have the sorted list then we are going to bind this list with the LongListSelector control. This is the exact thing we should do ..

Create FriendsInfo class....

Right click on the name of project in the solution explorer and add a new class name it as FriendsInfo.cs.
Add following code to FriendsInfo.cs class .. change the namespace to your project name ...


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace A_zGropedLongListSelectorApp
{
    public class FriendsInfo
    {
        public string Name {get; set;}
        public string ImgUrl { get; set; }
        public string Des { get; set; }

        public FriendsInfo(string name, string imgurl, string des)
        {
            this.Name = name;
            this.ImgUrl = imgurl;
            this.Des = des;
        }

    }
}


Create AlphaKeyGroup class....

Right click on the name of project in the solution explorer and add a new class name it as AlphaKeyGroup.cs.Add following code to AlphaKeyGroup.cs class .. change the namespace to your project name ...

using Microsoft.Phone.Globalization;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace A_zGropedLongListSelectorApp
{
    public class AlphaKeyGroup<T> : List<T>
    {
        /// <summary>
        /// The delegate that is used to get the key information.
        /// </summary>
        /// <param name="item">An object of type T</param>
        /// <returns>The key value to use for this object</returns>
        public delegate string GetKeyDelegate(T item);

        /// <summary>
        /// The Key of this group.
        /// </summary>
        public string Key { get; private set; }

        /// <summary>
        /// Public constructor.
        /// </summary>
        /// <param name="key">The key for this group.</param>
        public AlphaKeyGroup(string key)
        {
            Key = key;
        }

        /// <summary>
        /// Create a list of AlphaGroup<T> with keys set by a SortedLocaleGrouping.
        /// </summary>
        /// <param name="slg">The </param>
        /// <returns>Theitems source for a LongListSelector</returns>
        private static List<AlphaKeyGroup<T>> CreateGroups(SortedLocaleGrouping slg)
        {
            List<AlphaKeyGroup<T>> list = new List<AlphaKeyGroup<T>>();

            foreach (string key in slg.GroupDisplayNames)
            {
                list.Add(new AlphaKeyGroup<T>(key));
            }

            return list;
        }

        /// <summary>
        /// Create a list of AlphaGroup<T> with keys set by a SortedLocaleGrouping.
        /// </summary>
        /// <param name="items">The items to place in the groups.</param>
        /// <param name="ci">The CultureInfo to group and sort by.</param>
        /// <param name="getKey">A delegate to get the key from an item.</param>
        /// <param name="sort">Will sort the data if true.</param>
        /// <returns>An items source for a LongListSelector</returns>
        public static List<AlphaKeyGroup<T>> CreateGroups(IEnumerable<T> items, CultureInfo ci, GetKeyDelegate getKey, bool sort)
        {
            SortedLocaleGrouping slg = new SortedLocaleGrouping(ci);
            List<AlphaKeyGroup<T>> list = CreateGroups(slg);

            foreach (T item in items)
            {
                int index = 0;
                if (slg.SupportsPhonetics)
                {
                    //check if your database has yomi string for item
                    //if it does not, then do you want to generate Yomi or ask the user for this item.
                    //index = slg.GetGroupIndex(getKey(Yomiof(item)));
                }
                else
                {
                    index = slg.GetGroupIndex(getKey(item));
                }
                if (index >= 0 && index < list.Count)
                {
                    list[index].Add(item);
                }
            }

            if (sort)
            {
                foreach (AlphaKeyGroup<T> group in list)
                {
                    group.Sort((c0, c1) => { return ci.CompareInfo.Compare(getKey(c0), getKey(c1)); });
                }
            }

            return list;
        }


    }
}

Display the groped data in LongListSelector ....

Go to MainPage.xaml file copy and paste follwing xaml code .. then you should change 
x:Class="A_zGropedLongListSelectorApp.MainPage" to your project name like ..
x:Class="yourProjectName.MainPage"....

<phone:PhoneApplicationPage
    x:Class="A_zGropedLongListSelectorApp.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True">

    <phone:PhoneApplicationPage.Resources>
        <DataTemplate x:Key="PersonItemInfoTemplate">
            <StackPanel VerticalAlignment="Top" Orientation="Horizontal">
                <Image Source="{Binding ImgUrl}" Width="100" Height="100" Margin="5,0,0,0" />
                <StackPanel Orientation="Vertical">
                    <TextBlock FontWeight="Normal"  Text="{Binding Name}" Margin="10,0,0,0" FontFamily="Segoe WP Semibold" FontSize="26" Foreground="{StaticResource PhoneSemitransparentBrush}" />
                    <TextBlock FontWeight="Normal"  Text="{Binding Des}" Margin="10,0,0,0" FontFamily="Segoe WP Semibold" FontSize="18" Foreground="{StaticResource PhoneSemitransparentBrush}" />
                </StackPanel>
            </StackPanel>
        </DataTemplate>

        <DataTemplate x:Key="FriendsGroupHeaderTemplate">
            <Border Background="Transparent" Padding="5">
                <Border Background="{StaticResource PhoneAccentBrush}" BorderBrush="{StaticResource PhoneAccentBrush}" BorderThickness="2" Width="62" 
         Height="62" Margin="0,0,18,0" HorizontalAlignment="Left">
                    <TextBlock Text="{Binding Key}" Foreground="{StaticResource PhoneForegroundBrush}" FontSize="48" Padding="6" 
            FontFamily="{StaticResource PhoneFontFamilySemiLight}" HorizontalAlignment="Left" VerticalAlignment="Center"/>
                </Border>
            </Border>
        </DataTemplate>

        <phone:JumpListItemBackgroundConverter x:Key="BackgroundConverter"/>
        <phone:JumpListItemForegroundConverter x:Key="ForegroundConverter"/>
        <Style x:Key="FriendsJumpListStyle" TargetType="phone:LongListSelector">
            <Setter Property="GridCellSize"  Value="113,113"/>
            <Setter Property="LayoutMode" Value="Grid" />
            <Setter Property="ItemTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <Border Background="{Binding Converter={StaticResource BackgroundConverter}}" Width="113" Height="113" Margin="6" >
                            <TextBlock Text="{Binding Key}" FontFamily="{StaticResource PhoneFontFamilySemiBold}" FontSize="48" Padding="6" 
               Foreground="{Binding Converter={StaticResource ForegroundConverter}}" VerticalAlignment="Center"/>
                        </Border>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </Style>

    </phone:PhoneApplicationPage.Resources>

    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="{StaticResource PhoneTextHighContrastBrush}">
        <Grid.RowDefinitions>
            <RowDefinition Height="80"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        
        <!--header--> 
        <StackPanel Grid.Row="0" Background="#FF0035FF" Orientation="Horizontal">
            <Image VerticalAlignment="Center" Width="70" Height="70" Margin="0,0,0,0" Source="/Assets/Tiles/icon_signup.png"/>
            <TextBlock Text="My friends list" Margin="0,0,0,0" VerticalAlignment="Center" FontFamily="Segoe WP SemiLight" FontSize="36"/>
        </StackPanel>
        
        <!--LongListSelecttor binding with friends informations-->

        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="5,0,0,0">
            <phone:LongListSelector
                  x:Name="FriendsList"
                  JumpListStyle="{StaticResource FriendsJumpListStyle}"
                  Background="Transparent"
                  GroupHeaderTemplate="{StaticResource FriendsGroupHeaderTemplate}"
                  ItemTemplate="{StaticResource PersonItemInfoTemplate}"
                  LayoutMode="List"
                  IsGroupingEnabled="true"
                  HideEmptyGroups ="true"/>
        </Grid>
    </Grid>

</phone:PhoneApplicationPage>

Back-end Coding for MainPage.cs...

Add following c# code in to MainpPage.cs file ... 

Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using A_zGropedLongListSelectorApp.Resources;

namespace A_zGropedLongListSelectorApp
{
    /*
     * Coded By Sanka Bulathgama
     * sankabulathgama@outlook.com
     * +94711260261
     * http://www.csharpteacher.com/
     * http://sankabulathgama.wordpress.com/
     * https://www.facebook.com/seessri
    */
    public partial class MainPage : PhoneApplicationPage
    {
        /*
         * Create friends information list As FriendsInfoList
         */
        List<FriendsInfo> FriendsInfoList = new List<FriendsInfo>();
        public MainPage()
        {
            InitializeComponent();
            CreatePersonalInfoList();
            SortingListAZ();
        }

        /*
         * Add friends informations to the FriendsInfoList List
         */
        private void CreatePersonalInfoList()
        {
            FriendsInfoList.Add(new FriendsInfo("Sanka Bulathgama", "/Assets/Img/my.jpg", "www.csharpteacher.com"));            FriendsInfoList.Add(new FriendsInfo("Ann MMC", "/Assets/Img/my.jpg", "www.csharpteacher.com"));            FriendsInfoList.Add(new FriendsInfo("Astor", "/Assets/Img/my.jpg", "www.csharpteacher.com"));            FriendsInfoList.Add(new FriendsInfo("Anela WRD", "/Assets/Img/my.jpg", "www.csharpteacher.com"));            FriendsInfoList.Add(new FriendsInfo("Alison DEC", "/Assets/Img/my.jpg", "www.csharpteacher.com"));            FriendsInfoList.Add(new FriendsInfo("Brad", "/Assets/Img/my.jpg", "www.csharpteacher.com"));            FriendsInfoList.Add(new FriendsInfo("Boni", "/Assets/Img/my.jpg", "www.csharpteacher.com"));            FriendsInfoList.Add(new FriendsInfo("Corolein", "/Assets/Img/my.jpg", "www.csharpteacher.com"));            FriendsInfoList.Add(new FriendsInfo("Demon", "/Assets/Img/my.jpg", "www.csharpteacher.com"));            FriendsInfoList.Add(new FriendsInfo("Elaric", "/Assets/Img/my.jpg", "www.csharpteacher.com"));            FriendsInfoList.Add(new FriendsInfo("Fox", "/Assets/Img/my.jpg", "www.csharpteacher.com"));            FriendsInfoList.Add(new FriendsInfo("Ian Bell", "/Assets/Img/my.jpg", "www.csharpteacher.com"));            FriendsInfoList.Add(new FriendsInfo("Jaliya Udagedara", "/Assets/Img/my.jpg", "www.csharpteacher.com"));            FriendsInfoList.Add(new FriendsInfo("Klaus VD", "/Assets/Img/my.jpg", "www.csharpteacher.com"));            FriendsInfoList.Add(new FriendsInfo("Lenis BB", "/Assets/Img/my.jpg", "www.csharpteacher.com"));            FriendsInfoList.Add(new FriendsInfo("Matt VD", "/Assets/Img/my.jpg", "www.csharpteacher.com"));            FriendsInfoList.Add(new FriendsInfo("Fiqri Smile", "/Assets/Img/my.jpg", "www.csharpteacher.com"));            FriendsInfoList.Add(new FriendsInfo("Welington Perera", "/Assets/Img/my.jpg", "www.csharpteacher.com"));            FriendsInfoList.Add(new FriendsInfo("Sheldon Cooper", "/Assets/Img/my.jpg", "www.csharpteacher.com"));            FriendsInfoList.Add(new FriendsInfo("Penny BBT", "/Assets/Img/my.jpg", "www.csharpteacher.com"));            FriendsInfoList.Add(new FriendsInfo("Zee Mar", "/Assets/Img/my.jpg", "www.csharpteacher.com"));            FriendsInfoList.Add(new FriendsInfo("Trisha Mag", "/Assets/Img/my.jpg", "www.csharpteacher.com"));            FriendsInfoList.Add(new FriendsInfo("Dimple SI", "/Assets/Img/my.jpg", "www.csharpteacher.com"));            FriendsInfoList.Add(new FriendsInfo("Mom", "/Assets/Img/my.jpg", "www.csharpteacher.com"));
            FriendsInfoList.Add(new FriendsInfo("Dad", "/Assets/Img/my.jpg", "www.csharpteacher.com"));
            FriendsInfoList.Add(new FriendsInfo("Vanel Bidel", "/Assets/Img/my.jpg", "www.csharpteacher.com"));
        }

        /*
         * To convert a flat list of data into a list of lists grouped by a key
         */
        private void SortingListAZ()
        {
            List<AlphaKeyGroup<FriendsInfo>> DataSource = AlphaKeyGroup<FriendsInfo>.CreateGroups(FriendsInfoList,
                System.Threading.Thread.CurrentThread.CurrentUICulture,
                (FriendsInfo s) => { return s.Name; }, true);

            //Data bind the grouped list to the source of the LongListSelector control.

            FriendsList.ItemsSource = DataSource;

        }

    }
}

Finally...

Create a folder inside the Assets Folder.. name it as Img.. then add a image my.jpg to Img folder .. :) 


All done guys now you can run the app .. enjoy .. :) :).. if you need any deep down explanation ..please let me know ..   :)

Download Sample Project


Thank You :)














Comments

Popular posts from this blog

Load an Addin into DraftSight

These days i am developing two plugins for Autocad 2012 &  DraftSight 2013.so when i was developing the plugin i got in to big trouble.Normally in the Autocad , we can load the .dll file simply typing the command "NETLOAD" but in the Draftsight i could not able to do that. It said  " D:\c \projects\c projects\DSAddinCSharp1\ DSAddinCSharp1\bin\Debug\ DSAddinCSharp1.dll is not a valid add-in "

C# Character Escape Sequences

Character combinations consisting of a backslash ( \ ) followed by a letter or by a combination of digits are called "escape sequences." To represent a newline character, single quotation mark, or certain other characters in a character constant, you must use escape sequences. An escape sequence is regarded as a single character and is therefore valid as a character constant.

Imagine Cup 2014

Hi guys .. Get ready for imagine cup 2014 In NewZealand .In the next few days imagine cup 2013 finals will happen in Russia. So It is time to wear your thinking hat.You have one year to develop your marvelous ideas.  The Microsoft Imagine Cup is the world’s most prestigious student technology competition, bringing together student innovators from all over the world. If you have a great idea for a new app, bring it to life through Imagine Cup. Over the past 10 years, more than 1.65 million students from 190 countries have participated in the Imagine Cup.