Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing "close window" command with MVVM

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?

like image 420
mcalex Avatar asked Aug 14 '12 04:08

mcalex


People also ask

How do I close windows MVVM?

<local:ViewModel/> </Window. DataContext> <StackPanel>

How do I close a window in WPF?

Pressing ALT + F4 . Pressing the Close button. Pressing ESC when a button has the IsCancel property set to true on a modal window.

What is MVVM command?

Commands are an implementation of the ICommand interface that is part of the . NET Framework. This interface is used a lot in MVVM applications, but it is useful not only in XAML-based apps.


1 Answers

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:

public abstract class CloseableViewModel {     public event EventHandler ClosingRequest;      protected void OnClosingRequest()     {         if (this.ClosingRequest != null)         {             this.ClosingRequest(this, EventArgs.Empty);         }     } } 

Then in your ViewModel that inherits from CloseableViewModel, simply call this.OnClosingRequest(); for the Close command.

In the view:

public class YourView {     ...     var vm = new ClosableViewModel();     this.Datacontext = vm;     vm.ClosingRequest += (sender, e) => this.Close(); } 
like image 84
ken2k Avatar answered Oct 05 '22 18:10

ken2k