それでは、できあがったCounterComponentを使ったストアアプリ:CounterAppを作りましょうか。前回のstep3からCounterAppプロジェクトを丸ごとコピーし、プロジェクトプロパティでCounterComponentを参照します。
これでVisual StudioはConterComponentのトリセツである.winmdを読み、プロジェクトに抱き込んでくれます。ヘッダincludeパスの設定やライブラリのリンクなどは一切不要となるのは大きなメリットです。
CounterViewModelは以下のように修正します。
#pragma once
#include "Common/RelayCommand.h"
namespace CounterApp {
namespace cx {
namespace xaml = Windows::UI::Xaml;
namespace data = Windows::UI::Xaml::Data;
namespace input = Windows::UI::Xaml::Input;
}
[Windows::UI::Xaml::Data::Bindable]
public ref class CounterViewModel sealed : cx::data::INotifyPropertyChanged{
public:
CounterViewModel();
virtual event cx::data::PropertyChangedEventHandler^ PropertyChanged;
property int Count { int get(); }
property cx::input::ICommand^ Increment { cx::input::ICommand^ get(); }
property cx::input::ICommand^ Decrement { cx::input::ICommand^ get(); }
private:
void do_inc();
void do_dec();
void RaisePropertyChanged(Platform::String^ propertyName);
CounterComponent::Counter counter_;
};
}
#include "pch.h"
#include "CounterViewModel.h"
using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Data;
namespace CounterApp {
auto returnsTrue = [](Object^) { return true; };
CounterViewModel::CounterViewModel() { }
// property Count
int CounterViewModel::Count::get() { return counter_.Get(); }
// property Increment/Decrement
ICommand^ CounterViewModel::Increment::get() {
return ref new Common::RelayCommand(returnsTrue, [this](Object^) { do_inc(); });
}
ICommand^ CounterViewModel::Decrement::get() {
return ref new Common::RelayCommand(returnsTrue, [this](Object^) { do_dec(); });
}
// increment/decrement counter
void CounterViewModel::do_inc() {
int curr = counter_.Get();
counter_.Increment();
if (curr != counter_.Get()) {
RaisePropertyChanged(L"Count");
}
}
void CounterViewModel::do_dec() {
int curr = counter_.Get();
counter_.Decrement();
if (curr != counter_.Get()) {
RaisePropertyChanged(L"Count");
}
}
void CounterViewModel::RaisePropertyChanged(String^ propertyName) {
PropertyChanged(this, ref new PropertyChangedEventArgs(propertyName));
}
}
...はい、できあがり。

