Click here to Skip to main content
11,709,375 members (50,673 online)
Click here to Skip to main content

Handling a Window's Closed and Closing events in the View-Model

, 15 Apr 2010 CPOL 82.5K 2.2K 36
Rate this:
Please Sign up or sign in to vote.
This article discusses an attached behavior that lets you handle the View Window's Closed and Closing events via commands in the View-Model

Introduction

This article was inspired by Reed Copsey, Jr.'s Blend behavior which is up on the Expression Code Gallery. Reed's behavior uses a neat technique that lets the View-Model handle the Closing/Closed events of the View in an MVVM friendly manner. Since his code was tied to the Expression DLLs I thought it would be a good idea to write a plain WPF version. While similar in concept to the Blend behavior, I've slightly deviated from how the concept is implemented and also in how it's used. So this is not a direct 1-to-1 replacement though you should be able to get things working pretty much the same without too much effort.

The code idea is to allow a Window's Closed and Closing events to be handled via commands in the View-Model, and to get this going I wrote an attached behavior for the Window object.

Usage

The behavior exposes three commands:

  • Closed - This is executed when the Window.Closed event is fired.
  • Closing
    • Execute - This is executed if the Window.Closing event was not cancelled.
    • CanExecute - This is called when the Window.Closing event is fired, and gives you a chance to decide if you want to cancel or not.
  • CancelClosing - This is executed when the Window.Closing event is cancelled.

Here's an example of how you'd implement these commands in the View-Model. Notice how the example has MessageBox.Show calls in them, these are merely used to demonstrate how this works. You may want to use some kind of dependency injection to avoid direct UI code and instead use some kind of MessageBox service here (assuming you do want to prompt the user with a Yes/No message-box).

internal class MainViewModel : ViewModelBase
{
    private ObservableCollection<string> log = new ObservableCollection<string>();

    public ObservableCollection<string> Log
    {
        get { return log; }
    }

    private DelegateCommand exitCommand;

    public ICommand ExitCommand
    {
        get
        {
            if (exitCommand == null)
            {
                exitCommand = new DelegateCommand(Exit);
            }
            return exitCommand;
        }
    }

    private void Exit()
    {
        Application.Current.Shutdown();
    }

    private DelegateCommand closedCommand;

    public ICommand ClosedCommand
    {
        get
        {
            if (closedCommand == null)
            {
                closedCommand = new DelegateCommand(Closed);
            }
            return closedCommand;
        }
    }

    private void Closed()
    {
        log.Add("You won't see this of course! Closed command executed");
        MessageBox.Show("Closed");
    }

    private DelegateCommand closingCommand;

    public ICommand ClosingCommand
    {
        get
        {
            if (closingCommand == null)
            {
                closingCommand = new DelegateCommand(
                    ExecuteClosing, CanExecuteClosing);
            }
            return closingCommand;
        }
    }

    private void ExecuteClosing()
    {
        log.Add("Closing command executed");
        MessageBox.Show("Closing");
    }

    private bool CanExecuteClosing()
    {
        log.Add("Closing command execution check");

        return MessageBox.Show("OK to close?", "Confirm", 
            MessageBoxButton.YesNo) == MessageBoxResult.Yes;
    }

    private DelegateCommand cancelClosingCommand;

    public ICommand CancelClosingCommand
    {
        get
        {
            if (cancelClosingCommand == null)
            {
                cancelClosingCommand = new DelegateCommand(CancelClosing);
            }
            return cancelClosingCommand;
        }
    }

    private void CancelClosing()
    {
        log.Add("CancelClosing command executed");
        MessageBox.Show("CancelClosing");
    }
}

And here's how you attach the commands in the XAML.

<Window x:Class="WindowClosingDemo.MainWindow"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:nsmvvm="clr-namespace:NS.MVVM"
  <span class="code-attribute">nsmvvm:WindowClosingBehavior.Closed="{Binding ClosedCommand}"
  nsmvvm:WindowClosingBehavior.Closing="{Binding ClosingCommand}"
  nsmvvm:WindowClosingBehavior.CancelClosing="{Binding CancelClosingCommand}"</span>
  Title="MainWindow" Height="350" Width="525">

Implementation

Here's the code listing for the attached behavior. This listing has been reformatted to fit within 600 pixels.

public class WindowClosingBehavior
{
    public static ICommand GetClosed(DependencyObject obj)
    {
        return (ICommand)obj.GetValue(ClosedProperty);
    }

    public static void SetClosed(DependencyObject obj, ICommand value)
    {
        obj.SetValue(ClosedProperty, value);
    }

    public static readonly DependencyProperty ClosedProperty 
        = DependencyProperty.RegisterAttached(
        "Closed", typeof(ICommand), typeof(WindowClosingBehavior),
        new UIPropertyMetadata(new PropertyChangedCallback(ClosedChanged)));

    private static void ClosedChanged(
      DependencyObject target, DependencyPropertyChangedEventArgs e)
    {
        Window window = target as Window;
        
        if (window != null)
        {
            if (e.NewValue != <span class="code-keyword">null)
            {
                window.Closed += Window_Closed;
            }
            else
            {
                window.Closed -= Window_Closed;
            }</span>

I have highlighted the relevant portions in the code above. For the Closed event, we just execute any command if available since it's too late to worry about cancelling. For the Closing event, the CanExecute of the Closing command is used to determine if we are cancelling or not. If we are not cancelling, we execute the Closing command, else we execute a CancelClosing command if one is available. 

That's all. Thank you.

Reference

History

  • April 15, 2010 - Article first published

License

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

Share

About the Author

Nish Nishant
United States United States
Nish Nishant is a Software Architect/Consultant based out of Columbus, Ohio. He has over 15 years of software industry experience in various roles including Lead Software Architect, Principal Software Engineer, and Product Manager. Nish is a recipient of the annual Microsoft Visual C++ MVP Award since 2002 (13 consecutive awards as of 2014).

Nish is an industry acknowledged expert in the Microsoft technology stack. He authored
C++/CLI in Action for Manning Publications in 2005, and had previously co-authored
Extending MFC Applications with the .NET Framework for Addison Wesley in 2003. In addition, he has over 140 published technology articles on CodeProject.com and another 250+ blog articles on his
WordPress blog. Nish is vastly experienced in team management, mentoring teams, and directing all stages of software development.

Contact Nish : You can reach Nish on his google email id voidnish.

Website and Blog

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 5 Pin
Wayne Gaylard22-Jan-13 3:46
mentorWayne Gaylard22-Jan-13 3:46 
GeneralMy vote of 5 Pin
Sergiy Tkachuk6-Aug-12 13:16
memberSergiy Tkachuk6-Aug-12 13:16 
GeneralNice, but the menu does not work. Pin
Magnus Gudmundsson25-Jan-11 1:26
memberMagnus Gudmundsson25-Jan-11 1:26 
Hi Nishant.

If I press exit in the menu, and then answer no to the OkToClose question,
I get the cancelclose msgbox, and then
I get the closing msgbox, and the program exits,
surely that is not the expected behavior?

I am running vs 2010.

Cheers Magnus
GeneralRe: Nice, but the menu does not work. Pin
Nishant Sivakumar25-Jan-11 4:26
mvpNishant Sivakumar25-Jan-11 4:26 
GeneralRe: Nice, but the menu does not work. Pin
Magnus Gudmundsson25-Jan-11 22:02
memberMagnus Gudmundsson25-Jan-11 22:02 
GeneralRe: Nice, but the menu does not work. Pin
Nishant Sivakumar26-Jan-11 2:02
mvpNishant Sivakumar26-Jan-11 2:02 
GeneralGood stuff, this what I do in CInch too Pin
Sacha Barber15-Apr-10 20:39
mvpSacha Barber15-Apr-10 20:39 
GeneralRe: Good stuff, this what I do in CInch too Pin
Nishant Sivakumar16-Apr-10 1:24
mvpNishant Sivakumar16-Apr-10 1:24 
GeneralRe: Good stuff, this what I do in CInch too Pin
Alan Beasley18-Apr-10 0:43
memberAlan Beasley18-Apr-10 0:43 
GeneralRe: Good stuff, this what I do in CInch too Pin
Alan Beasley18-Apr-10 0:40
memberAlan Beasley18-Apr-10 0:40 
GeneralRe: Good stuff, this what I do in CInch too Pin
Sacha Barber18-Apr-10 1:03
mvpSacha Barber18-Apr-10 1:03 
GeneralRe: Good stuff, this what I do in CInch too Pin
Alan Beasley19-Apr-10 0:24
memberAlan Beasley19-Apr-10 0:24 
GeneralRe: Good stuff, this what I do in CInch too Pin
Sacha Barber19-Apr-10 4:10
mvpSacha Barber19-Apr-10 4:10 
GeneralRe: Good stuff, this what I do in CInch too Pin
Pete O'Hanlon19-Apr-10 11:26
mvpPete O'Hanlon19-Apr-10 11:26 
GeneralRe: Good stuff, this what I do in CInch too Pin
Sacha Barber19-Apr-10 20:58
mvpSacha Barber19-Apr-10 20:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150819.1 | Last Updated 15 Apr 2010
Article Copyright 2010 by Nish Nishant
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid