Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

WPF: Close command on the Window close button

0.00/5 (No votes)
8 Sep 2009 1  
I could not find a good solution to this anywhere, so here is mine (which I think is a bit of an abuse of attached properties, but hey ho!).

Problem

I have an ExitApplication command that I want to execute when I click the ‘x’ on the main window. There does not seem to be any way to expose the Close button without overriding the control template of the window. I did not want to write code-behind even though in this case it may be the most pragmatic approach! Nonetheless, I was determined to find an alternative.

My solution (with a suggestion from a colleague) is to create an attached property for the command, and when the set property method is called, I could bind to the Closed event which would execute the attached command. And here is my code:

C#
public static class WindowAttachedProperties
{
    public static readonly DependencyProperty
            CloseCommand =
            DependencyProperty.RegisterAttached(
            "CloseCommand",
            typeof(ICommand),
            typeof(Window));

    public static ICommand GetCloseCommand(
        Window windowTarget)
    {
        throw new NotImplementedException(
        "The close command attached property "+
        "was not intended to be used outsite of the "+
        "closing even of a window.");
    }

    public static void SetCloseCommand(
       Window windowTarget, ICommand value)
    {
        // hack : because not setting property
        // just binding to an event!
        windowTarget.Closed += new EventHandler(
            (sender, args) =>
                    {
                        value.Execute(null);
                    });
    }
}

I would love to hear of a ‘better’ way of doing this!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here