InvokeCommandActionは、イベントに応じてコマンドを呼び出す仕組みです。
Windowの開閉(Loaded/Closing)やマウスクリックなどのイベントを捕捉して処理を実行します。
トリガーはインタラクションを引き起こすもので、ユーザーのアクションを促すものです。
そして、インタラクショントリガーに対応して実行されるものがアクションです。
XAMLには下記のように定義します。
<i:Interaction.Triggers> <i:EventTrigger EventName="XXXX"> <prism:InvokeCommandAction Command="{Binding XXXX}"/> </i:EventTrigger> </i:Interaction.Triggers>
using Prism.Commands; using Prism.Mvvm; using System; namespace WpfPrismMvvm { public class MainWindowViewModel : BindableBase { private string _updatedText; public string UpdateText { get { return _updatedText; } set { SetProperty(ref _updatedText, value); } } public DelegateCommand<EventArgs> LoadedAction { get; private set; } public DelegateCommand<EventArgs> CloseAction { get; private set; } public DelegateCommand TextBlockClickedCommand { get; private set; } public MainWindowViewModel() { LoadedAction = new DelegateCommand<EventArgs>(x => actionEvent(x)); CloseAction = new DelegateCommand<EventArgs>(x => actionEvent(x)); TextBlockClickedCommand = new DelegateCommand(() => { UpdateText = $"Updated: {DateTime.Now}"; }) ; } // イベント処理 private void actionEvent(EventArgs e) { System.Console.WriteLine(e.ToString()); } } }
<Window x:Class="WpfPrismMvvm.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:prism="http://prismlibrary.com/" xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" mc:Ignorable="d" Title="MainWindow" Height="200" Width="300"> <i:Interaction.Triggers> <!-- ウィンドウを閉じた場合のイベント定義 --> <i:EventTrigger EventName="Closing"> <prism:InvokeCommandAction Command="{Binding CloseAction}"/> </i:EventTrigger> <i:EventTrigger EventName="Loaded"> <prism:InvokeCommandAction Command="{Binding LoadedAction}"/> </i:EventTrigger> </i:Interaction.Triggers> <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"> <!-- クリック要求用テキストブロック --> <TextBlock Text="Click Me!" HorizontalAlignment="Center" Background="LightBlue"> <!-- テキストブロックをマウスクリックした場合のイベント定義 --> <i:Interaction.Triggers> <i:EventTrigger EventName="MouseDown"> <i:InvokeCommandAction Command="{Binding TextBlockClickedCommand}"/> </i:EventTrigger> </i:Interaction.Triggers> </TextBlock> <!-- 結果出力用テキストブロック --> <TextBlock Text="{Binding UpdateText}" FontSize="14" Margin="10"/> </StackPanel> </Window>