The easiest way is to implement ButtonClick event handler and invoke Window.Close() method, but how doing this through a Command binding?
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"> <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)
Actually, it is possible without C# code. The key is to use interactions:
<Button Content="Close"> <i:Interaction.Triggers> <i:EventTrigger EventName="Click"> <ei:CallMethodAction TargetObject="{Binding ElementName=window}" MethodName="Close"/> </i:EventTrigger> </i:Interaction.Triggers> </Button> In order for this to work, just set the x:Name of your window to "window", and add these two namespaces:
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions" 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With