65.9K
CodeProject is changing. Read more.
Home

WPF: Close command on the Window close button

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.33/5 (2 votes)

Sep 8, 2009

GPL3
viewsIcon

52543

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:

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!