[Windowsストアアプリ開発]GridViewを使ったサンプルの作成

2013.02.27

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

目次に移動

前回はListViewを使ったアプリを作りました。今回はGridViewを使ってみたいと思います。
作ったのは画像のようにグループ分けしたタイルを表示するだけの簡単なサンプルです。

win-store-app-gridview4

画面を実装する

まずは新しくプロジェクトを作成してください。テンプレートは「新しいアプリケーション」にします。
作成できたら MainPage.xaml を開いて以下のように実装してください。

<Page
    x:Class="SampleGridView.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:SampleGridView"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Page.Resources>
        <CollectionViewSource x:Name="MySource" IsSourceGrouped="True" ItemsPath="Items"/>
    </Page.Resources>

    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <GridView
            Padding="100,100,100,100"
            ItemTemplate="{StaticResource Standard250x250ItemTemplate}"
            ItemsSource="{Binding Source={StaticResource MySource}}"
            SelectionMode="None"
            IsSwipeEnabled="False">

            <GridView.ItemsPanel>
                <ItemsPanelTemplate>
                    <VirtualizingStackPanel Orientation="Horizontal"/>
                </ItemsPanelTemplate>
            </GridView.ItemsPanel>

            <GridView.GroupStyle>
                <GroupStyle>
                    <GroupStyle.HeaderTemplate>
                        <DataTemplate>
                            <TextBlock
                                Text="{Binding Title}"
                                Margin="3,-7,10,10"
                                Style="{StaticResource GroupHeaderTextStyle}" />
                        </DataTemplate>
                    </GroupStyle.HeaderTemplate>

                    <GroupStyle.Panel>
                        <ItemsPanelTemplate>
                            <VariableSizedWrapGrid Orientation="Vertical" Margin="0,0,80,0"/>
                        </ItemsPanelTemplate>
                    </GroupStyle.Panel>
                </GroupStyle>
            </GridView.GroupStyle>
        </GridView>
    </Grid>
</Page>

ポイントだけ簡単に説明します。前回の ListViewの時はItemsSourceプロパティにObservableCollectionオブジェクトを直接渡していました。今回は11行目でページのリソースに CollectionViewSource を定義してGridViewのItemsSource にバインドしています。なぜこんなことをしているのかというとこの方法を使わないとGridViewをグループ化することができなかったためです。GridViewをグループ表示するためにはその他に CollectionViewSourceのIsSourceGroupedプロパティをTrueにすることとItemsPathにプロパティ名を指定することが必要です。GridViewのItemTemplateって何?って方は前回書いたので下のリンクからそちらをご覧ください。

[Windowsストアアプリ開発]ListViewを使ったサンプルの作成 - ListViewのItemTemplateとは

データモデルを実装する

次にGridViewに代入するデータ型を定義します。プロジェクトにDataModelというフォルダを追加してその中にSampleDataGroup.cs、SampleDataItem.csというファイルを作成して下さい。
これらはデータの入れ物になります。今回はグループの中にタイルのコレクションが含まれるので階層構造にする必要があります。

SampleDataGroup.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;

namespace SampleGridView.DataModel
{
    class SampleDataGroup
    {
        public SampleDataGroup(String title)
        {
            this._title = title;
        }

        private string _title = string.Empty;
        public string Title
        {
            get { return this._title; }
            set { this._title = value; }
        }

        private ObservableCollection<SampleDataItem> _items = new ObservableCollection<SampleDataItem>();
        public ObservableCollection<SampleDataItem> Items
        {
            get { return this._items; }
        }
    }
}

Titleはグループのヘッダーに表示される文字列です。Main.xamlを見ると33行目でバインディングされているのが分かると思います。
CollectionViewSourceのItemsPathに指定しているItemsというのはこのクラスの25行目のプロパティ名のことです。

SampleDataItem.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;

namespace SampleGridView.DataModel
{
    class SampleDataItem
    {
        private static Uri _baseUri = new Uri("ms-appx:///");

        public SampleDataItem(String title, String subtitle, String imagePath)
        {
            this._title = title;
            this._subtitle = subtitle;
            this._imagePath = imagePath;
        }

        private string _title = string.Empty;
        public string Title
        {
            get { return this._title; }
            set { this._title = value; }
        }

        private string _subtitle = string.Empty;
        public string Subtitle
        {
            get { return this._subtitle; }
            set { this._subtitle = value; }
        }

        private ImageSource _image = null;
        private String _imagePath = null;
        public ImageSource Image
        {
            get
            {
                if (this._image == null && this._imagePath != null)
                {
                    this._image = new BitmapImage(new Uri(_baseUri, this._imagePath));
                }
                return this._image;
            }

            set
            {
                this._imagePath = null;
                this._image = value;
            }
        }

        public void SetImage(String path)
        {
            this._image = null;
            this._imagePath = path;
        }
    }
}

これは前回のListViewのサンプルものとほぼ同じです。

GridViewにデータを代入する処理を実装する

最後にMainPage.xaml.csを実装します。まずは以下の名前空間をusingディレクティブに追加してください。

using System.Collections.ObjectModel;
using SampleGridView.DataModel;


起動時にCollectionViewSourceにデータを代入する処理を入れて終わりです。

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    createGroups();
}

private void createGroups()
{
    var groups = new ObservableCollection<SampleDataGroup>();

    var group1 = new SampleDataGroup("Group 1");
    group1.Items.Add(new SampleDataItem("Title 1-1",
            "SubTitle 1-1",
            "Assets/Logo.png"));

    group1.Items.Add(new SampleDataItem("Title 1-2",
            "SubTitle 1-2",
            "Assets/Logo.png"));

    group1.Items.Add(new SampleDataItem("Title 1-3",
            "SubTitle 1-3",
            "Assets/Logo.png"));

    group1.Items.Add(new SampleDataItem("Title 1-4",
            "SubTitle 1-4",
            "Assets/Logo.png"));

    group1.Items.Add(new SampleDataItem("Title 1-5",
            "SubTitle 1-5",
            "Assets/Logo.png"));
    groups.Add(group1);

    // 以下は繰り返しなので省略します。
    
    MySource.Source = groups;
}

目次に移動