So my first attempt did everything out of the code behind, and now I'm trying to refactor my code to use the MVVM pattern, following the guidance of the MVVM in the box information.
I've created a viewmodel class to match my view class, and I'm moving the code out of the code behind into the viewmodel starting with the commands.
My first snag is trying to implement a 'Close' button that closes the window if the data has not been modified. I've rigged up a CloseCommand to replace the 'onClick' method and all is good except for where the code tries to run this.Close()
. Obviously, since the code has been moved from a window to a normal class, 'this' isn't a window and therefore isn't closeable. However, according to MVVM, the viewmodel doesn't know about the view, so i can't call view.Close()
.
Can someone suggest how I can close the window from the viewmodel command?
Given a way, Please check
https://stackoverflow.com/a/30546407/3659387
Short Description
first of all give your window a name like
on my close button I've defined Command and Command Parameter like
then in my view model
Watch out for trendy paradigms. MVVM can be useful, but you really shouldn't treat it as a rigid set of rules. Use your own judgement, and when it doesn't make sense - don't use it.
The solutions provided here (with the exception of @RV1987's solution) are a very good example of things getting out of hands. You are replacing a single
Close()
call with such a huge amount of code, for what purpose? You gain absolutely nothing from moving the closing code from the view to the view-model. The only thing you gain is room for more bugs.Now, I'm not saying MVVM is to be ignored. Quite the contrary, it can be very useful. Just don't over do it.
This solution is quick and easy. Downside is that there is some coupling between the layers.
In your viewmodel:
using MVVM-light toolkit:
In the ViewModel:
And in the View:
I personally use a very simple approach: for every ViewModel that is related to a closeable View, I created a base ViewModel like this following example:
Then in your ViewModel that inherits from
CloseableViewModel
, simply callthis.OnClosingRequest();
for theClose
command.In the view: