How to bind Close command to a button

WpfButtonWpf ControlsCommandbinding

Wpf Problem Overview

The easiest way is to implement ButtonClick event handler and invoke Window.Close() method, but how doing this through a Command binding?

Wpf Solutions

Solution 1 - Wpf

All it takes is a bit of XAML...

<Window x:Class="WCSamples.Window1"
        <CommandBinding Command="ApplicationCommands.Close"
    <StackPanel Name="MainStackPanel">
        <Button Command="ApplicationCommands.Close" 
                Content="Close Window" />

And a bit of C#...

private void CloseCommandHandler(object sender, ExecutedRoutedEventArgs e)

(adapted from this MSDN article)

Solution 2 - Wpf

Actually, it is possible without C# code. The key is to use interactions:

<Button Content="Close">
    <i:EventTrigger EventName="Click">
      <ei:CallMethodAction TargetObject="{Binding ElementName=window}" MethodName="Close"/>

In order for this to work, just set the x:Name of your window to "window", and add these two namespaces:


This requires that you add the Expression Blend SDK DLL to your project, specifically Microsoft.Expression.Interactions.

In case you don't have Blend, the SDK can be downloaded here.

Solution 3 - Wpf

I think that in real world scenarios a simple click handler is probably better than over-complicated command-based systems but you can do something like that:

using RelayCommand from this article

public class MyCommands
    public static readonly ICommand CloseCommand =
        new RelayCommand( o => ((Window)o).Close() );

<Button Content="Close Window"
        Command="{X:Static local:MyCommands.CloseCommand}"
        CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, 
                           AncestorType={x:Type Window}}}"/>

Solution 4 - Wpf

If the window was shown with Window.ShowDialog():

The simplest solution that I know of is to set the IsCancel property to true of the close Button:

<Button Content="Close" IsCancel="True" />

No bindings needed, WPF will do that for you automatically!

This properties provide an easy way of saying these are the "OK" and "Cancel" buttons on a dialog. It also binds the ESC key to the button.

Reference: MSDN Button.IsCancel property.

Solution 5 - Wpf

For .NET 4.5 SystemCommands class will do the trick (.NET 4.0 users can use WPF Shell Extension google - Microsoft.Windows.Shell or Nicholas Solution).

        <CommandBinding Command="{x:Static SystemCommands.CloseWindowCommand}" 
                        Executed="CloseWindow_Exec" />
    <!-- Binding Close Command to the button control -->
    <Button ToolTip="Close Window" Content="Close" Command="{x:Static SystemCommands.CloseWindowCommand}"/>

In the Code Behind you can implement the handlers like this:

    private void CloseWindow_CanExec(object sender, CanExecuteRoutedEventArgs e)
        e.CanExecute = true;

    private void CloseWindow_Exec(object sender, ExecutedRoutedEventArgs e)

Solution 6 - Wpf

In the beginning I was also having a bit of trouble figuring out how this works so I wanted to post a better explanation of what is actually going on.

According to my research the best way to handle things like this is using the Command Bindings. What happens is a "Message" is broadcast to everything in the program. So what you have to do is use the CommandBinding. What this essentially does is say "When you hear this Message do this".

So in the Question the User is trying to Close the Window. The first thing we need to do is setup our Functions that will be called when the SystemCommand.CloseWindowCommand is broadcast. Optionally you can assign a Function that determines if the Command should be executed. An example would be closing a Form and checking if the User has saved.

MainWindow.xaml.cs (Or other Code-Behind)

void CloseApp( object target, ExecutedRoutedEventArgs e ) {
	/*** Code to check for State before Closing ***/

void CloseAppCanExecute( object sender, CanExecuteRoutedEventArgs e ) {
	/*** Logic to Determine if it is safe to Close the Window ***/
    e.CanExecute = true;

Now we need to setup the "Connection" between the SystemCommands.CloseWindowCommand and the CloseApp and CloseAppCanExecute

MainWindow.xaml (Or anything that implements CommandBindings)

    <CommandBinding Command="SystemCommands.CloseWindowCommand"

You can omit the CanExecute if you know that the Command should be able to always be executed Save might be a good example depending on the Application. Here is a Example:

    <CommandBinding Command="SystemCommands.CloseWindowCommand"

Finally you need to tell the UIElement to send out the CloseWindowCommand.

<Button Command="SystemCommands.CloseWindowCommand">

Its actually a very simple thing to do, just setup the link between the Command and the actual Function to Execute then tell the Control to send out the Command to the rest of your program saying "Ok everyone run your Functions for the Command CloseWindowCommand".

This is actually a very nice way of handing this because, you can reuse the Executed Function all over without having a wrapper like you would with say WinForms (using a ClickEvent and calling a function within the Event Function) like:

protected override void OnClick(EventArgs e){
	/*** Function to Execute ***/

In WPF you attach the Function to a Command and tell the UIElement to execute the Function attached to the Command instead.

I hope this clears things up...

Solution 7 - Wpf

One option that I've found to work is to set this function up as a Behavior.

The Behavior:

    public class WindowCloseBehavior : Behavior<Window>
    public bool Close
        get { return (bool) GetValue(CloseTriggerProperty); }
        set { SetValue(CloseTriggerProperty, value); }

    public static readonly DependencyProperty CloseTriggerProperty =
        DependencyProperty.Register("Close", typeof(bool), typeof(WindowCloseBehavior),
            new PropertyMetadata(false, OnCloseTriggerChanged));

    private static void OnCloseTriggerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        var behavior = d as WindowCloseBehavior;

        if (behavior != null)

    private void OnCloseTriggerChanged()
        // when closetrigger is true, close the window
        if (this.Close)

On the XAML Window, you set up a reference to it and bind the Behavior's Close property to a Boolean "Close" property on your ViewModel:

    <behavior:WindowCloseBehavior Close="{Binding Close}" />

So, from the View assign an ICommand to change the Close property on the ViewModel which is bound to the Behavior's Close property. When the PropertyChanged event is fired the Behavior fires the OnCloseTriggerChanged event and closes the AssociatedObject... which is the Window.


All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioniLemmingView Question on Stackoverflow
Solution 1 - WpfNicholas ArmstrongView Answer on Stackoverflow
Solution 2 - WpftheDmiView Answer on Stackoverflow
Solution 3 - WpfNirView Answer on Stackoverflow
Solution 4 - WpfpogosamaView Answer on Stackoverflow
Solution 5 - WpfkiranView Answer on Stackoverflow
Solution 6 - WpfAndy BrahamView Answer on Stackoverflow
Solution 7 - WpfJoel PalmerView Answer on Stackoverflow