Xamarin.MacでCocoa Bindingを使う
Interface Builderとソースコードを連動させるCocoa Bindingの使い方を調査している。
「Cocoa Binding」はXamarin.Macの「Bindingライブラリ(いわゆるP/Invokeみたいなもの)」と名称が似ているがまったくの別物である。
実装1編集
- バインディング用のプロパティを用意する。
- Export属性でInterface Builderから見た場合の名称を与える。
- WillChangeValueメソッドおよびDidChangeValueメソッドでプロパティの変更を伝える。
この例では配列を作るのが面倒だったのでAVFoundationのビデオ入力デバイス一覧を使っている。FaceTimeカメラなんかが列挙されるはず。
AVCaptureDevice[] _videoDevices;
[Export("videoDevices")]
public AVCaptureDevice[] VideoDevices
{
get { return _videoDevices; }
set
{
if (_videoDevices != value)
{
WillChangeValue("videoDevices");
_videoDevices = value;
DidChangeValue("videoDevices");
}
}
}
public override void WindowDidLoad()
{
base.WindowDidLoad();
this.VideoDevices = AVCaptureDevice.DevicesWithMediaType(AVMediaType.Video);
}
Interface Builderを開きバインディングを設定する。
- Bindings Inspectorを開く
- Value Selection
- Content
- Bind to 「Files's Owner」を選びチェック
- Model Key Path 「videoDevices」(Exportで指定したプロパティ名称)
- null許容の場合は「Inserts Null Placeholder」にチェック
- Content Values
- Bind to 「Files's Owner」を選びチェック
- Model Key Path 「videoDevices.localizedName」(Exportで指定したプロパティのプロパティが表示名となる)
- null許容の場合は「Inserts Null Placeholder」にチェック
- Content
自動選択を使う場合は「Selected〜」系にも値を埋める。
備考1編集
Nullable型のプロパティはバインディングとして利用できない。実行時に落ちる。
DateTime? ReservedAt { get; set; }