XAMLといえば、WPF、Silverlight、Windows Phone、WindowsストアアプリなどのプロジェクトでViewを定義する優れものマークアップ言語ですが、なぜか、WindowsストアアプリのXAMLではBehaviorがありませんでした。
Behaviorがないと何が困るかといえば、
- XAML上のオブジェクトをクリックしたタイミングでStoryBoardを呼び出したい
- オブジェクトの操作をコードを書かないで実行したい
のようなことができないからです。
「あれ?それって普通できないから、コードビハインド側(xaml.vbとかxaml.csとか)に記述しますよね?」
と思われるかもしれませんが、Behaviorはこの常識を打ち破ってしまう仕組みで、WPF時代にすでに実装(SilverlightはSilverlight3からなので玲ちゃんのときから)されている既存テクノロジーなのです。
知らなければ特に不満はないのですが、知っていてBehaviorを使っていた人にとっては、XAMLなのにBehaviorがないのはWindowsストアアプリのViewを作る上で非常にフラストレーションがたまるものであり、また、View分離前提でチーム開発するうえでの足かせになっていたのです。
それが、Blend for Visual Studio 2013 RCでWindows 8.1ストアアプリのプロジェクトを作成したときにサポートされるようになりました。
ただし、あくまでも現状はWindows 8.1用のWindowsストアアプリプロジェクトが対象のようで、Windows 8 用Windowsストアアプリプロジェクトの場合の[アセット]-[ビヘイビアー]表示は次のようになっており「download additional behaviors」とはなっていますが、クリックしても追加ビヘイビアーはありません。
今回サポートされたBehaviorは次の10個です。
- CallMethodAction : 指定したオブジェクトのメソッドを呼び出す
- ChangePropertyAction : 指定したオブジェクトのプロパティを変更する
- ControlStoryboardAction : 指定したStoryboardの動きを制御する
- DataTriggerBehavior : Binding値が条件に一致したときにActionを実行するトリガー
- EventTriggerBehavior : イベントが発生したときにActionを実行するトリガー
- GoToStateAction : 指定したオブジェクトのViewStateに書かれたStoryBoradを起動する
- IncrementalUpdateBehavior :
- InvokeCommandAction : 指定したオブジェクトのイベントに対してICommandなオブジェクトをBindingする
- NavigateToPageAction : ページ間の移動を定義する
- PlaySoundAction : 指定したサウンドを再生する
それでは簡単にビヘイビアーの使い方を見てみましょう。
[アセット]-[ビヘイビアー]-[CallMethodAction]をドラッグして画面上のCommandにドロップします。
この操作だけでButtonコントロールにEventTriggerBehaviorが追加され、更にそこで起動されるActionとしてCallMethodActionが追加されます。
CallMethodActionのプロパティでMediaElementのPlayメソッドを割り当てましょう。
<grid grid.row="1">
<grid.rowdefinitions>
<rowdefinition height="*">
<rowdefinition height="Auto">
</rowdefinition>
<mediaelement x:name="myME" margin="1,1,0,0" autoplay="False" source="ms-appx:///Video/ThroughTheWindow.mp4">
<mediaelement.projection>
<planeprojection>
</planeprojection>
</mediaelement.projection>
<stackpanel grid.row="1" orientation="Horizontal">
<button x:name="playButton" content="再生" margin="8,8,0,8" width="204" fontsize="24">
<interactivity:interaction.behaviors>
<core:eventtriggerbehavior eventname="Click">
<core:callmethodaction targetobject="{Binding ElementName=myME}" methodname="Play">
</core:callmethodaction>
</core:eventtriggerbehavior>
</interactivity:interaction.behaviors></button>
<button x:name="pauseButton" content="一時停止" margin="8,8,0,8" width="204" fontsize="24" />
<button x:name="stopButton" content="停止" margin="0,8,12,8" width="204" fontsize="24" />
</stackpanel>
</mediaelement>
</grid>
ここまでで実行して「再生」ボタンをクリックすると動画が始まります。
ここまででxaml.vbもxaml.csも登場しません。
XAMLの世界だけで完結しています。「再生」ボタンをクリックしたときにView側だけで完結するのであれば、ViewModelにICommandを実装してメソッドを実行したり、Bindingしたり、コードビハインドを使ってViewModelのメソッドを実行する必要はありません。