今回はC#+WPF+Prismを用いる時に、ClickイベントをViewModel側にどう通知するのかを紹介したいと思います。
やりたいこと
この画面から

クリックすると、「Clicked」のMessageBoxが表示される。

フォルダ構成

ViewにButtonのアクション関数をバインド
肝となるところは、Button
のCommand="{Binding ClickCommand}"
の箇所。
通常、Prismを利用しない場合だと、Click="Click_Button"
といった書き方で、さらにMainWindow.csにそのアクション関数を定義します。
しかし、PrismではMVVMの思想に基づいて、ViewModelにその定義をするので、通常とは異なる記述の仕方になっています。
ViewModelでアクション関数を定義
using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Windows;
namespace Sample.ViewModels
{
public class MainWindowViewModel : BindableBase
{
private string _title = "Prism Application";
public DelegateCommand ClickCommand { get; set; }
public string Title
{
get { return _title; }
set { SetProperty(ref _title, value); }
}
public MainWindowViewModel()
{
ClickCommand = new DelegateCommand(OnClick);
}
private void OnClick()
{
MessageBox.Show("Clicked");
}
}
}
まず、DelegateCommand
を定義します。
public DelegateCommand ClickCommand { get; set; }
次に、その定義したCommandとアクション関数を紐づけます。
ClickCommand = new DelegateCommand(OnClick);
あとは、OnClick
を定義してあげれば完了です。
おわりに
実際のコードはこちらにあります。
https://github.com/ishikawa-takumi/SamplePrism/tree/master/Sample