プログラミングとかブログ

Unity/C#/SRPGStudio/RPGツクールMVの情報とかその他気になったことを調べて書きます。

【C#】ボタン等のイベントからバインドソースのメソッドが実行されるようにする方法【XAML】

MVVMはコードビハインド絶対殺すマンなので使いたくありません。
Commandでもいいんですが定義するのが面倒なのでビヘイビア使います。
EventTriggerBehaviorとCallMethodActionを使うと任意のイベントからViewModel(というかデータコンテキスト)のメソッドを実行できます。
Commandとはなんだったのか

コード

たぶんBlendでやったほうが早いと思います。

//XAML
<Page
    x:Class="UWPtest2.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:UWPtest2"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:Interactivity="using:Microsoft.Xaml.Interactivity" 
    xmlns:Core="using:Microsoft.Xaml.Interactions.Core"
    mc:Ignorable="d">

    <Page.DataContext>
        <local:ViewModel />
    </Page.DataContext>

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

        <Button x:Name="button" Content="Button" Margin="0,33,0,295">
            <Interactivity:Interaction.Behaviors>
                <Core:EventTriggerBehavior EventName="Click">
                    <Core:CallMethodAction MethodName="Greet" TargetObject="{Binding Mode=TwoWay}"/>
                </Core:EventTriggerBehavior>
            </Interactivity:Interaction.Behaviors>
            
        </Button>
    </Grid>
</Page>

//ViewModel
using System;
using Windows.UI.Popups;

namespace UWPtest2
{
    class ViewModel
    {
        public async void Greet()
        {
            await new MessageDialog("こんにちは", "タイトル").ShowAsync();
        }   
    }
}

結果

ボタンをクリックするとメッセージダイアログが出ます。
f:id:shirakamisauto:20160721225638g:plain


参考
Blendを使う場合のViewModelクラス - かずきのBlog@hatena
かずきのUWP入門というPDFをSlideShareに公開しました - かずきのBlog@hatena
なおビヘイビアを使うにはNugetからBlendのをとってくる必要があります。
UWPのBehaviorを使う | Qaramell Blog