■ ListBox 클래스 : ListCollectionView를 이용해 GroupStyle 설정하기

----------------------------------------------------------------------------------------------------

...

 

<ListBox Name="listBox">

    <ListBox.ItemTemplate>

    ...

    </ListBox.ItemTemplate>

    <ListBox.GroupStyle>

        <GroupStyle>

            <GroupStyle.HeaderTemplate>

                <DataTemplate>

                    <TextBlock

                        Margin="6"

                        Foreground="White"

                        Background="DarkGray"

                        FontWeight="Bold"

                        FontSize="12pt"

                        Text="{Binding Path=Name}" />

                </DataTemplate>

            </GroupStyle.HeaderTemplate>

        </GroupStyle>

    </ListBox.GroupStyle>

</ListBox>

 

...

 

using System;

using System.Collections.ObjectModel;

using System.ComponentModel;

using System.Globalization;

using System.Windows.Data;

 

...

 

/// <summary>

/// 기간 그룹 설명자

/// </summary>

public class PeriodGroupDescription : GroupDescription

{

    //////////////////////////////////////////////////////////////////////////////////////////////////// Method

    ////////////////////////////////////////////////////////////////////////////////////////// Public

 

    #region 항목에서 그룹 명칭 구하기 - GroupNameFromItem(item, level, cultureInfo)

 

    /// <summary>

    /// 항목에서 그룹 명칭 구하기

    /// </summary>

    /// <param name="item">항목</param>

    /// <param name="level">레벨</param>

    /// <param name="cultureInfo">CultureInfo 객체</param>

    /// <returns>그룹 명칭</returns>

    public override object GroupNameFromItem(object item, int level, CultureInfo cultureInfo)

    {

        Person person = item as Person;

 

        if(person.BirthDate == null)

        {

            return "Unknown";

        }

 

        int year = ((DateTime)person.BirthDate).Year;

 

        if(year < 1575) return "Pre-Baroque";

        if(year < 1725) return "Baroque";

        if(year < 1795) return "Classical";

        if(year < 1870) return "Romantic";

        if(year < 1910) return "20th Century";

 

        return "Post-War";

    }

 

    #endregion

}

 

...

 

ObservableCollection<Person> observableCollection = new ObservableCollection<Person>();

 

...

 

ListCollectionView listCollectionView = new ListCollectionView(observableCollection);

 

listCollectionView.SortDescriptions.Add(new SortDescription("BirthDate", ListSortDirection.Ascending));

 

listCollectionView.GroupDescriptions.Add(new PeriodGroupDescription());

 

...

 

this.listBox.ItemsSource = listCollectionView;

 

if(this.listBox.Items.Count > 0)

{

    this.listBox.SelectedIndex = 0;

}

----------------------------------------------------------------------------------------------------

Posted by 사용자 icodebroker
TAG

댓글을 달아 주세요