MVVM Tips: How to close the current window / dialog?

To keep your ViewModel separated from the View we would like to make sure the ViewModel knows as little about the UI as possible, this includes no hard references. So how do we close the window?

I like to create a abstract ViewModel class specifically for this purpose which extends from my ViewModel base class and adds an event called RequestClose. Lets call it CloseableViewModel.

public abstract class CloseableViewModel : ViewModel
{
    public event EventHandler RequestClose;

    protected OnRequestClose()
    {
        if (RequestClose != null)
            RequestClose(this, EventArgs.Empty);
    }
}

Now just make sure your view model extends the CloseableViewModel. When you are linking your ViewModel to your view add a listener to the event

public partial class DialogView : ChildWindow
{
    public DialogView(DialogViewModel model)
    {
        this.DataContext = model;
        model.RequestClose += delegate (object sender, EventArgs args) { this.Close(); }
    }
}

When you want to close the window from your ViewModel call OnRequestClose();

Easy as that, and your ViewModel doesn’t need to know about your View 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s