XAMLにデータを提供するCounterViewModelにHistoryプロパティを追加しましょう。ふやす/へらすボタンが押されたとき、OperationRecordを操作履歴に追加することを忘れずに。
#pragma once
#include "Common/BindableBase.h" // Common::BindableBase
#include "CounterLib/CounterLib.h" // Counterlib::Counter
#include "OperationRecord.h" // OperationRecord
#include <memory> // std::uniqur_ptr
namespace CounterApp {
[Windows::UI::Xaml::Data::Bindable]
public ref class CounterViewModel sealed : Common::BindableBase, Windows::UI::Xaml::Input::ICommand {
typedef Windows::UI::Xaml::Input::ICommand command_type;
typedef Platform::Object object;
typedef Windows::Foundation::EventHandler<object^> event_type;
public:
CounterViewModel();
// properties
property int Count { int get(); }
property command_type^ Modify { command_type^ get(); }
property Windows::Foundation::Collections::IVector<OperationRecord^>^ History {
Windows::Foundation::Collections::IVector<OperationRecord^>^ get();
}
// ICommand requirements
virtual void Execute(object^ parameter);
virtual bool CanExecute(object^ parameter);
virtual event event_type^ CanExecuteChanged;
private:
void increment();
void decrement();
std::unique_ptr<CounterLib::Counter> counter_;
Platform::Collections::Vector<OperationRecord^> history_;
};
}
#include "pch.h"
#include "CounterViewModel.h"
using namespace Platform;
using namespace Windows::UI::Xaml::Input;
namespace CounterApp {
CounterViewModel::CounterViewModel() : counter_(new CounterLib::BoundedCounter(0,9)) {
history_.Append(ref new OperationRecord(L"うごきはじめた"));
}
// properties
int CounterViewModel::Count::get() { return counter_->get(); }
ICommand^ CounterViewModel::Modify::get() { return this; }
// ICommand implementations
void CounterViewModel::Execute(Object^ arg) {
String^ cmd = dynamic_cast<String^>(arg);
if ( cmd != nullptr ) {
if ( cmd == L"Increment" ) increment();
else
if ( cmd == L"Decrement" ) decrement();
}
}
bool CounterViewModel::CanExecute(Object^ arg) {
String^ cmd = dynamic_cast<String^>(arg);
if ( cmd != nullptr ) {
if ( cmd == L"Increment" ) return counter_->can_increment();
else
if ( cmd == L"Decrement" ) return counter_->can_decrement();
}
return false;
}
void CounterViewModel::increment() {
counter_->increment();
history_.Append(ref new OperationRecord(L"ちょびっとふえた"));
OnPropertyChanged(L"Count");
CanExecuteChanged(this, nullptr);
}
void CounterViewModel::decrement() {
counter_->decrement();
history_.Append(ref new OperationRecord(L"ちょびっとへった"));
OnPropertyChanged(L"Count");
CanExecuteChanged(this, nullptr);
}
Windows::Foundation::Collections::IVector<OperationRecord^>^ CounterViewModel::History::get() {
return %history_;
}
}
Historyプロパティの型はWindows::Foundation::Collections::IVector<OperationRecord^>^つまりOperationRecord^の列を表すインターフェースであり、実際に返すのはPlatform::Collections::Vector<OperationRecord^>^です。XAMLさんはListViewを描画する際にHistoryからデータ列を受け取り、さらにそのデータ列の各要素からWhatとWhenを取り出すわけです。
