Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind Close command to a button

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

like image 278
iLemming Avatar asked Jun 30 '09 20:06

iLemming


Video Answer


2 Answers

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)

like image 155
Nicholas Armstrong Avatar answered Sep 26 '22 09:09

Nicholas Armstrong


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.

like image 33
theDmi Avatar answered Sep 22 '22 09:09

theDmi