Implementing "close window" command with MVVM Implementing "close window" command with MVVM wpf wpf

Implementing "close window" command with MVVM


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();}


You don't need to pass the View instance to your ViewModel layer. You can access the main window like this -

Application.Current.MainWindow.Close()

I see no issue in accessing your main window in ViewModel class as stated above. As per MVVM principle there should not be tight coupling between your View and ViewModel i.e. they should work be oblivious of others operation. Here, we are not passing anything to ViewModel from View. If you want to look for other options this might help you - Close window using MVVM


My solution to close a window from view model while clicking a button is as follows:

In view model

public RelayCommand CloseWindow;Constructor(){    CloseWindow = new RelayCommand(CloseWin);}public void CloseWin(object obj){    Window win = obj as Window;    win.Close();}

In View, set as follows

<Button Command="{Binding CloseWindowCommand}" CommandParameter="{Binding ElementName=WindowNameTobeClose}" Content="Cancel" />