views:

1316

answers:

2

The easiest way is to implement ButtonClick event handler and invoke Window.Close() method. But how to do this through a command binding?

+6  A: 

All it takes is a bit of XAML...

<Window x:Class="WCSamples.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt;
    <Window.CommandBindings>
        <CommandBinding Command="ApplicationCommands.Close"
                        Executed="CloseCommandHandler"/>
    </Window.CommandBindings>
    <StackPanel Name="MainStackPanel">
        <Button Command="ApplicationCommands.Close" 
                Content="Close Window" />
    </StackPanel>
</Window>

And a bit of C#...

private void CloseCommandHandler(object sender, ExecutedRoutedEventArgs e)
{
    this.Close();
}

(adapted from this MSDN article)

Nicholas Armstrong
phew... I thought it's possible to do this without c# code. Then It seems better to do this in an old way of defining ButtonClick behavior.
Ike
The benefit of using commands is that they aren't tied to specific UI controls; you can use this one command to close your application using a button, a menu option, or even a keyboard shortcut, all through the same command. And, while the functionality doesn't really apply to the 'Close' operation, commands also provide a way to automatically disable the corresponding UI control when they aren't able to be fired - the way 'Paste' is disabled when no text is in the clipboard.
Nicholas Armstrong
+3  A: 

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 http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

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}}}"/>
Nir