简体   繁体   中英

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.

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

Just override the Closing event and do this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM