WPF MVVM cancel window closing

2019-07-08 09:12发布

问题:

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.

回答1:

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).



回答2:

Just override the Closing event and do this:

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


标签: .net wpf mvvm