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 i开发者_开发知识库t'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;
精彩评论