Click here to Skip to main content
15,891,529 members
Articles / Desktop Programming / WPF
Tip/Trick

Closing View from ViewModel

Rate me:
Please Sign up or sign in to vote.
4.75/5 (3 votes)
27 Feb 2013CPOL2 min read 48.2K   1.7K   18  
Lightweight approach to close view from viewmodel command.

Introduction 

This short article presents a walk-through of how to close a WPF application from the View Model.

Background

Closing/starting a window is UI interaction (owned by the view) and should be decoupled from the view model. The view model should contain Commands and Properties (as needed for the view).

View model can also contain events to which the view can respond. In the approach presented in this article, a view model event is used to trigger an action owned by the view.

There are already multiple approaches to this problem:

  1. Using Attached Behavior
  2. Using Application level service/controller to manage application life cycle
  3. Using Message Bus (like MVVM Light Messenger/Prism Event Aggregator)

The approach mentioned in this article is a trimmed down version of the above approaches for a small WPF application (where an Attached Behavior or Application service are overkill).

Approach    

In this approach, a RequestClose event will be added to the ViewModel. The view model will raise a RequestClose event and the view will respond to it by invoking the Close method.

The event wire up and the view-viewmodel binding is done in the Application startup override.

Using the Code   

The code is written in VS2012 RTM. It should be opened in VS2010/VS2012RTM/VS2012 as Visual Studio projects / solutions are now backwards compatible. The application uses MVVM Light (for an MVVM based framework).

The demo application contains a single window with a button "Close Me". Clicking on this button invokes a CloseCommand on the view model that in turn raises a RequestClose event. The view handler then closes the instance (on listening to the RequestClose event).

  1. Create an ICloseable interface that defines the RequestClose event. The ViewModel should implement the ICloseable interface if it supports Closeable behavior.
  2. C#
    interface ICloseable
    {
       event EventHandler<EventArgs> RequestClose;
    }
  3. Implement ICloseable in the view model.
  4. C#
    class MainWindowViewModel : ViewModelBase, ICloseable 
  5. Add a CloseComm<code>and to the view model.
  6. C#
    public ICommand CloseCommand { get; private set; }    
  7. Wire-up a RequestClose event in the Loaded event of the View code behind, if DataContext implements the ICloseable interface.
  8. C#
    Loaded += (s, e) =>
     {
       if (DataContext is ICloseable)
       {
           (DataContext as ICloseable).RequestClose += (_, __) => this.Close();
       }
     };
    
  9. View-viewmodel binding is done in the Application Startup.
  10. C#
    protected override void OnStartup(StartupEventArgs e)
    { 
        base.OnStartup(e);
    
        // Create Main Window instance
        MainWindow window = new MainWindow();
    
        // Create Main Window View Model
        MainWindowViewModel viewModel = new MainWindowViewModel();
    
        // Associate DataContext
        window.DataContext = viewModel;
    
        Application.Current.MainWindow = window;
        window.Show();
    }
  11. StartupURI should be removed from MainWindow.xaml.

Points of Interest  

The following refinements are useful:

  1. View view-model binding can be moved from OnStartup to ViewModelLocator.  Refer to this blog for View ViewModel binding approaches.
  2. Event wire-up can be refreshed on DataContext change notification.

History  

This is the second version of the article. In this revision, the ICloseable interface is introduced and event wire up for the RequestClose event has been moved to the View.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
Software Engineer based out in Noida.

Technology skillset – .NET, WPF, WCF, LINQ, XAML.

Started blogging on http://1wpf.wordpress.com/


Stackoverflow Profile -> http://stackoverflow.com/users/649524/tilak

Comments and Discussions

 
-- There are no messages in this forum --