[WPF] One of the methods to close the window from ViewModel

1 minute read

What is this article

I’m making an app with WPF.
I searched for ** how to close the window from ViewModel **, but none of them came to my mind.
Write your own conclusions (methods) that are good points from various articles.

(Assumption)

  • There is one button in Window1.xaml.
  • Click that button to close the window.

View
Find the parent Window of the button and execute CloseWindow with it as an argument.
CloseWindow is implemented in ViewModel described later.

Window1.xaml


<Button Command="{Binding CloseWindow}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}" Content="Close" />

ViewModel
Declare the command with ReactiveProperty and write the content of the process in the constructor.

I cast it with System.Windows.Window and .Close () , but
Actually, you should do null check properly.

Window1ViewModel.cs


//Property declaration
public ReactiveCommand CloseWindow { get; } = new ReactiveCommand();

//In the constructor
CloseWindow.Subscribe(x => ((System.Windows.Window)x).Close());

use

Press the OK / Cancel button in the window
** Instead of closing the window immediately **
** If you want to display a confirmation dialog and then close the window **.

Window1.xaml


<Button Command="{Binding OK}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}" Content="OK button" />

Window1ViewModel.cs


//In the constructor
OK.Subscribe(x => {
    result = MessageBox.Show("Are you sure you want to close the window?", "Confirmation message", MessageBoxButtons.OKCancel);
    if (result == DialogResult.Cancel)
        return;
    else
        CloseWindow.Execute(x);
});

Finally

I’m sure there is a better way

reference

Implemented processing to close the window only with xaml (www.neko3cs.net)

Postscript 2020.08.17

After receiving comments and googled with Trigger Action, I arrived at the correct answer in no time.
Close window with MVVM –Qiita

I will write an article after searching more properly.
Thank you very much.

Postscript 2020.08.27

You introduced the related video in the comment. Thank you very much.
YouTube video (skip the intro and start from 120 seconds)