10
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

MVVMでウインドウを閉じる

Last updated at Posted at 2019-01-11

#やりたいこと
ViewModelからウインドウを閉じる。

#実装
ウインドウを閉じるアクションを作成する。

アクション
using System.Windows;
using System.Windows.Interactivity;

namespace Sample {
    public class CloseWindowAction : TriggerAction<FrameworkElement> {
        protected override void Invoke(object parameter)
            => Window.GetWindow(AssociatedObject).Close();
    }
}

#使い方

XAML
<Window x:Class="Sample.MainView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
        xmlns:prism="http://prismlibrary.com/"
        xmlns:local="clr-namespace:Sample"
        Title="MainView" Height="300" Width="300">
    <i:Interaction.Triggers>
        <prism:InteractionRequestTrigger SourceObject="{Binding CloseWindowRequest, Mode=OneWay}">
            <local:CloseWindowAction/>
        </prism:InteractionRequestTrigger>
    </i:Interaction.Triggers>
    <Grid>
        <TextBox />
    </Grid>
</Window>
ViewModel
using Prism.Interactivity.InteractionRequest;
using System.Windows;

namespace Sample {
    public class MainViewModel {
        public InteractionRequest<Notification> CloseWindowRequest { get; }
            = new InteractionRequest<Notification>();

        private void CloseWindow()
            => CloseWindowRequest.Raise(null);
    }
}
10
14
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
10
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?