LoginSignup
1
2

More than 5 years have passed since last update.

ViewModelから画面を閉じる処理

Last updated at Posted at 2019-02-03

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>
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2