Xamarin.Forms CollectionView 그룹화

Download Sample 샘플 다운로드

큰 데이터 집합은 계속해서 스크롤하는 목록에 표시될 때 다루기 어려울 수 있습니다. 이 시나리오에서 데이터를 그룹으로 구성하면 데이터를 보다 쉽게 탐색할 수 있으므로 사용자 환경이 향상될 수 있습니다.

CollectionView 는 그룹화된 데이터 표시를 지원하고 표시되는 방법을 제어하는 다음 속성을 정의합니다.

  • IsGrouped형식 bool의 는 기본 데이터를 그룹에 표시해야 하는지 여부를 나타냅니다. 이 속성의 기본값은 false입니다.
  • GroupHeaderTemplateDataTemplate그룹의 헤더에 사용할 템플릿 형식의 입니다.
  • GroupFooterTemplate각 그룹의 바닥글에 사용할 템플릿인 형식 DataTemplate의 입니다.

이러한 속성은 개체에 의해 BindableProperty 지원되므로 속성이 데이터 바인딩의 대상이 될 수 있습니다.

다음 스크린샷은 그룹화된 데이터를 표시하는 것을 보여 CollectionView 줍니다.

Screenshot of a grouped data in a CollectionView, on iOS and Android

데이터 템플릿에 대한 자세한 내용은 Xamarin.Forms 데이터 템플릿을 참조하세요.

데이터 그룹화

데이터를 표시하려면 먼저 데이터를 그룹화해야 합니다. 이 작업은 각 그룹이 항목 목록인 그룹 목록을 만들어 수행할 수 있습니다. 그룹 목록은 두 개의 데이터를 정의하는 컬렉션 T 이어야 IEnumerable<T> 합니다.

  • 그룹 이름입니다.
  • IEnumerable 그룹에 속하는 항목을 정의하는 컬렉션입니다.

따라서 데이터를 그룹화하기 위한 프로세스는 다음과 같습니다.

  • 단일 항목을 모델하는 형식을 만듭니다.
  • 단일 항목 그룹을 모델로 하는 형식을 만듭니다.
  • IEnumerable<T> 단일 항목 그룹을 모델로 하는 형식인 컬렉션을 T 만듭니다. 따라서 이 컬렉션은 그룹화된 데이터를 저장하는 그룹의 컬렉션입니다.
  • 컬렉션에 데이터를 추가합니다 IEnumerable<T> .

예시

데이터를 그룹화할 때 첫 번째 단계는 단일 항목을 모델링하는 형식을 만드는 것입니다. 다음 예제에서는 샘플 애플리케이션의 Animal 클래스를 보여줍니다.

public class Animal
{
    public string Name { get; set; }
    public string Location { get; set; }
    public string Details { get; set; }
    public string ImageUrl { get; set; }
}

클래스는 Animal 단일 항목을 모델화합니다. 그런 다음 항목 그룹을 모델로 하는 형식을 만들 수 있습니다. 다음 예제에서는 샘플 애플리케이션의 AnimalGroup 클래스를 보여줍니다.

public class AnimalGroup : List<Animal>
{
    public string Name { get; private set; }

    public AnimalGroup(string name, List<Animal> animals) : base(animals)
    {
        Name = name;
    }
}

클래스는 AnimalGroup 클래스에서 List<T> 상속되고 그룹 이름을 나타내는 속성을 추가 Name 합니다.

IEnumerable<T> 그런 다음 그룹 컬렉션을 만들 수 있습니다.

public List<AnimalGroup> Animals { get; private set; } = new List<AnimalGroup>();

이 코드는 컬렉션의 각 항목이 개체인 명명 AnimalsAnimalGroup 컬렉션을 정의합니다. 각 AnimalGroup 개체는 이름 및 List<Animal> 그룹의 개체를 정의하는 컬렉션으로 구성됩니다 Animal .

그런 다음 그룹화된 데이터를 컬렉션에 추가할 수 있습니다.Animals

Animals.Add(new AnimalGroup("Bears", new List<Animal>
{
    new Animal
    {
        Name = "American Black Bear",
        Location = "North America",
        Details = "Details about the bear go here.",
        ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/0/08/01_Schwarzbär.jpg"
    },
    new Animal
    {
        Name = "Asian Black Bear",
        Location = "Asia",
        Details = "Details about the bear go here.",
        ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b7/Ursus_thibetanus_3_%28Wroclaw_zoo%29.JPG/180px-Ursus_thibetanus_3_%28Wroclaw_zoo%29.JPG"
    },
    // ...
}));

Animals.Add(new AnimalGroup("Monkeys", new List<Animal>
{
    new Animal
    {
        Name = "Baboon",
        Location = "Africa & Asia",
        Details = "Details about the monkey go here.",
        ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/f/fc/Papio_anubis_%28Serengeti%2C_2009%29.jpg/200px-Papio_anubis_%28Serengeti%2C_2009%29.jpg"
    },
    new Animal
    {
        Name = "Capuchin Monkey",
        Location = "Central & South America",
        Details = "Details about the monkey go here.",
        ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/4/40/Capuchin_Costa_Rica.jpg/200px-Capuchin_Costa_Rica.jpg"
    },
    new Animal
    {
        Name = "Blue Monkey",
        Location = "Central and East Africa",
        Details = "Details about the monkey go here.",
        ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/BlueMonkey.jpg/220px-BlueMonkey.jpg"
    },
    // ...
}));

이 코드는 컬렉션에 Animals 두 개의 그룹을 만듭니다. 첫 번째 AnimalGroup 이름은 곰 Bears세부 정보 컬렉션을 포함합니다 List<Animal> . 두 번째 AnimalGroup 이름은 이름이 지정 Monkeys되며 원숭이 세부 정보 컬렉션을 포함합니다 List<Animal> .

그룹화된 데이터 표시

CollectionView 는 다음으로 속성을 설정 IsGrouped 하여 데이터가 올바르게 그룹화된 경우 그룹화된 데이터를 표시합니다 true.

<CollectionView ItemsSource="{Binding Animals}"
                IsGrouped="true">
    <CollectionView.ItemTemplate>
        <DataTemplate>
            <Grid Padding="10">
                ...
                <Image Grid.RowSpan="2"
                       Source="{Binding ImageUrl}"
                       Aspect="AspectFill"
                       HeightRequest="60"
                       WidthRequest="60" />
                <Label Grid.Column="1"
                       Text="{Binding Name}"
                       FontAttributes="Bold" />
                <Label Grid.Row="1"
                       Grid.Column="1"
                       Text="{Binding Location}"
                       FontAttributes="Italic"
                       VerticalOptions="End" />
            </Grid>
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>

해당하는 C# 코드는 다음과 같습니다.

CollectionView collectionView = new CollectionView
{
    IsGrouped = true
};
collectionView.SetBinding(ItemsView.ItemsSourceProperty, "Animals");
// ...

속성에 있는 CollectionView 각 항목의 모양은 속성을 DataTemplate/a0>로 설정 CollectionView.ItemTemplate 하여 정의됩니다. 자세한 내용은 항목 모양 정의를 참조 하세요.

참고 항목

기본적으로 CollectionView 그룹 머리글 및 바닥글에 그룹 이름이 표시됩니다. 이 동작은 그룹 머리글 및 그룹 바닥글을 사용자 지정하여 변경할 수 있습니다.

그룹 헤더 사용자 지정

속성을 DataTemplate다음으로 설정하여 각 그룹 헤더의 CollectionView.GroupHeaderTemplate 모양을 사용자 지정할 수 있습니다.

<CollectionView ItemsSource="{Binding Animals}"
                IsGrouped="true">
    ...
    <CollectionView.GroupHeaderTemplate>
        <DataTemplate>
            <Label Text="{Binding Name}"
                   BackgroundColor="LightGray"
                   FontSize="Large"
                   FontAttributes="Bold" />
        </DataTemplate>
    </CollectionView.GroupHeaderTemplate>
</CollectionView>

이 예제에서 각 그룹 머리글은 그룹 이름을 표시하고 다른 모양 속성이 설정된 것으로 설정 Label 됩니다. 다음 스크린샷은 사용자 지정된 그룹 헤더를 보여 줍니다.

Screenshot of a customized group header in a CollectionView, on iOS and Android

속성을 DataTemplate다음으로 설정하여 각 그룹 바닥글의 CollectionView.GroupFooterTemplate 모양을 사용자 지정할 수 있습니다.

<CollectionView ItemsSource="{Binding Animals}"
                IsGrouped="true">
    ...
    <CollectionView.GroupFooterTemplate>
        <DataTemplate>
            <Label Text="{Binding Count, StringFormat='Total animals: {0:D}'}"
                   Margin="0,0,0,10" />
        </DataTemplate>
    </CollectionView.GroupFooterTemplate>
</CollectionView>

이 예제에서는 각 그룹 바닥글이 그룹의 항목 수를 표시하는 바닥글로 설정 Label 됩니다. 다음 스크린샷은 사용자 지정된 그룹 바닥글을 보여 줍니다.

Screenshot of a customized group footer in a CollectionView, on iOS and Android

빈 그룹

CollectionView 그룹화된 데이터를 표시하면 비어 있는 모든 그룹이 표시됩니다. 이러한 그룹은 그룹이 비어 있음을 나타내는 그룹 머리글 및 바닥글과 함께 표시됩니다. 다음 스크린샷은 빈 그룹을 보여 줍니다.

Screenshot of an empty group in a CollectionView, on iOS and Android

참고 항목

iOS 10 이하에서는 빈 그룹의 그룹 머리글과 바닥글이 모두 위쪽 CollectionView에 표시될 수 있습니다.

템플릿이 없는 그룹화

CollectionView 는 속성을 다음으로 설정 CollectionView.ItemTemplate 하지 않고 올바르게 그룹화된 데이터를 표시할 수 있습니다 DataTemplate.

<CollectionView ItemsSource="{Binding Animals}"
                IsGrouped="true" />

이 시나리오에서는 단일 항목을 모델링하는 형식과 단일 항목 그룹을 모델링하는 ToString 형식의 메서드를 재정의하여 의미 있는 데이터를 표시할 수 있습니다.