サンプルファイルではstep3,step4が本アーティクルに対応します。
データ列とのバインディング
ことはじめとことはじめ(2)で解説したのはUI要素の基本のキであるTextBlock(とButton)の扱いでした。TextBlockは"1つ"のデータと利用者とを繋ぐ窓口として機能します。ならば"複数"のデータ(データ列)についてはどうなんだ、と。
ここまでのサンプル:CounterAppに操作履歴:Historyをくっつけてみました。
HistoryはXAMLコントロールの一つ:ListViewで実現しており、ListViewに並ぶ各項は何をやったか(What)といつやったか(When)をTextBlockの二段重ねで構成しています。
XAMLを見ていただきましょうか:
<Grid Grid.Row="1" x:Name="CounterPage"> <!-- x:Name をココに移動 -->
<Grid.ColumnDefinitions>
<ColumnDefinition Width="120"/>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="2*"/> <!-- 一列追加: ここにListViewを置く -->
</Grid.ColumnDefinitions>
<Grid Grid.Column="1" >
<TextBlock ... />
<Button ... />
<Button ... />
</Grid>
<!-- 新たに追加: ここから -->
<ListView Grid.Column="2" ItemsSource="{Binding History}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding What}" FontSize="40"/>
<TextBlock Text="{Binding When}" FontSize="20"/>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<!-- 新たに追加: ここまで -->
</Grid>
XAML上にListViewを置き、ItemsSource="{Binding History}"とすることでデータ提供側のHistoryプロパティにバインドします。
ListViewの各項はItemTemplate内のDataTemplateで定義しています。2つのTextBlockをStackPanelで二段重ねにし、それぞれWhatとWhenにバインド。"What/Whenの2つのプロパティを持ったナニか"の列を返すプロパティ:Historyをデータ提供側が用意することになりますな。
"What/Whenの2つのプロパティを持ったナニか"を作ります。
#pragma once
namespace CounterApp {
[Windows::UI::Xaml::Data::Bindable]
public ref class OperationRecord sealed {
public:
OperationRecord(Platform::String^ what, Windows::Foundation::DateTime when);
OperationRecord(Platform::String^ what);
property Platform::String^ What;
property Windows::Foundation::DateTime When;
private:
static Windows::Globalization::Calendar cal_;
};
}
#include "pch.h"
#include "OperationRecord.h"
namespace CounterApp {
OperationRecord::OperationRecord(Platform::String^ what, Windows::Foundation::DateTime when) {
What = what;
When = when;
}
OperationRecord::OperationRecord(Platform::String^ what) {
What = what;
When = cal_.GetDateTime();
}
Windows::Globalization::Calendar OperationRecord::cal_;
}
WhatとWhenはそれぞれString^とDateTimeです。

