Edited at

ViewModelから画面を閉じる処理


ViewModelから画面を閉じる処理

画面を閉じる処理を通して処理の追加方法の例を示します。

見やすいよう一部省略や改行位置を変更しています。


Action

View側の画面を閉じる処理。

using Prism.Interactivity.InteractionRequest;

using System.Windows;
using System.Windows.Interactivity;

namespace Sample.ViewUtilities {
public class CloseWindowAction : TriggerAction<DependencyObject> {
protected override void Invoke(object parameter) {
if (parameter is InteractionRequestedEventArgs e) {
Invoke(AssociatedObject, e);
}
}

private void Invoke(DependencyObject sender,
InteractionRequestedEventArgs e) {
if (sender is Window window) {
window.Close();
e.Callback?.Invoke();
}
}
}
}


ViewModel

Viewに画面を閉じる処理を指示。

public InteractionRequest<Notification> CloseWindowRequest { get; private set; }

public DelegateCommand CloseWindowCommand { get; private set; }

public SampleWindowViewModel() {
CloseWindowRequest = new InteractionRequest<Notification>();
CloseWindowCommand = new DelegateCommand(ExecuteCloseWindowCommand,
CanExecuteCloseWindowCommand);
}

private bool CanExecuteCloseWindowCommand() {
return true;
}

private void ExecuteCloseWindowCommand() {
CloseWindowRequest.Raise(null);
}


XAML

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

xmlns:prism="http://www.codeplex.com/prism"
xmlns:ViewUtilities="clr-namespace:Sample.ViewUtilities"
・・・
<i:Interaction.Triggers>
<prism:InteractionRequestTrigger
SourceObject="{Binding CloseWindowRequest}">
<ViewUtilities:CloseWindowAction/>
</prism:InteractionRequestTrigger>
</i:Interaction.Triggers>
・・・
<Window.InputBindings>
<KeyBinding Modifiers="Ctrl" Key="W"
Command="{Binding CloseWindowCommand, Mode=OneWay}"/>
</Window.InputBindings>
・・・
<Menu>
<MenuItem Header="ファイル(_F)">
<MenuItem Header="閉じる(_X)"
Command="{Binding CloseWindowCommand, Mode=OneWay}"/>
</MenuItem>
</Menu>