prostynick
prostynick

Reputation: 6219

WPF MVVM cancel window closing

I am new to WPF and MVVM. I would like to minimize the window instead of closing it. In other words, I would like to cancel Closing event of window and minimize this window.

How should I do that MVVM way?

If it's relevant, at the end I will set ShowInTaskbar to false and use WinForms tray component.

Upvotes: 2

Views: 2402

Answers (2)

Wonko the Sane
Wonko the Sane

Reputation: 10823

The common misunderstanding with MVVM is that there can never, ever be code-behind in a view. That is simply not true.

The goal of MVVM is to minimize the code in the code-behind, but for things that directly interact with the view itself (such as Windows events), it is acceptable to put in some code-behind. The code-behind would handle the Cancel, and may do the minimize, or call a command in the ViewModel, or some other such thing.

Otherwise, you are going to have to come up with a convoluted system of handling the event in the ViewModel, which breaks the MVVM pattern by having the ViewModel have a reference to the View (instead of the other way around).

Upvotes: 9

Botz3000
Botz3000

Reputation: 39650

Just override the Closing event and do this:

e.Cancel = true;
this.ShowInTaskbar = false;
this.WindowState = WindowState.Minimized;

Upvotes: 1

Related Questions