--- title: "How to: Enable a Command" ms.date: "03/30/2017" dev_langs: - "csharp" - "vb" helpviewer_keywords: - "CommandBindings [WPF]" - "commanding [WPF]" ms.assetid: d8016266-58d9-48f7-8298-a86b7ed49fbd --- # How to: Enable a Command The following example demonstrates how to use commanding in Windows Presentation Foundation (WPF). The example shows how to associate a to a , create a , and create the event handlers which implement the . For more information on commanding, see the [Commanding Overview](commanding-overview.md). ## Example The first section of code creates the user interface (UI), which consists of a and a , and creates a that associates the command handlers with the . The property of the is associated with the command. The is added to the of the root . The and event handlers are attached to this binding and associated with the command. Without the there is no command logic, only a mechanism to invoke the command. When the is clicked, the is raised on the command target followed by the . These events traverse the element tree looking for a for that particular command. It is worth noting that because tunnel and bubble through the element tree, care must be taken in where the is put. If the is on a sibling of the command target or another node that is not on the route of the , the will not be accessed. [!code-xaml[EnableCloseCommand#CloseCommandBinding](~/samples/snippets/csharp/VS_Snippets_Wpf/EnableCloseCommand/CSharp/Window1.xaml#closecommandbinding)] [!code-csharp[EnableCloseCommand#CloseCommandBindingCodeBehind](~/samples/snippets/csharp/VS_Snippets_Wpf/EnableCloseCommand/CSharp/Window1.xaml.cs#closecommandbindingcodebehind)] [!code-vb[EnableCloseCommand#CloseCommandBindingCodeBehind](~/samples/snippets/visualbasic/VS_Snippets_Wpf/EnableCloseCommand/VisualBasic/Window1.xaml.vb#closecommandbindingcodebehind)] The next section of code implements the and event handlers. The handler calls a method to close the open file. The handler calls a method to determine whether a file is open. If a file is open, is set to `true`; otherwise, it is set to `false`. [!code-csharp[EnableCloseCommand#CloseCommandHandler](~/samples/snippets/csharp/VS_Snippets_Wpf/EnableCloseCommand/CSharp/Window1.xaml.cs#closecommandhandler)] [!code-vb[EnableCloseCommand#CloseCommandHandler](~/samples/snippets/visualbasic/VS_Snippets_Wpf/EnableCloseCommand/VisualBasic/Window1.xaml.vb#closecommandhandler)] ## See also - [Commanding Overview](commanding-overview.md)