BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Windows Presentation Foundation
.NET 4.0+

WPF Commanding - Using Application Commands

The one hundred and sixty-fourth part of the Windows Presentation Foundation Fundamentals tutorial begins a look at commanding. This allows reusable commands to be linked to controls, providing separation of user interface and functionality.

Adding a Command Binding to a Control

Controls that support commanding include properties that you can use to identify the command that should be executed in response to user actions. In many cases, there is a Command property for this purpose. For custom commands, you use special binding syntax to link the property to the command. For built-in commands you simply provide the fully-qualified name of the member providing the functionality.

Let's add three new menu items within the "Edit" menu. We'll link these to commands that provide clipboard functionality. These are retrieved from the ApplicationCommands class's Cut, Copy and Paste properties.

Add the following within the existing MenuItem's XAML element:

<MenuItem Command="ApplicationCommands.Cut"/>
<MenuItem Command="ApplicationCommands.Copy"/>
<MenuItem Command="ApplicationCommands.Paste"/>

You can now run the program to try the commands. Type some text into the text box, then select part of it. With a selection present, the cut and copy commands are automatically enabled. If you deselect the text, they become disabled. If you cut or copy information to the clipboard, the paste command become available but only whilst the text box has the keyboard focus. Executing the command pastes the text into the box at the current position.

Note that the menu items show the standard text for cut, copy and paste. They also display the default shortcut keys, which should execute the commands when they are enabled. This information is provided by the RoutedUICommands and used automatically, although you can override it within the MenuItem, should you wish.

WPF basic commanding with menu

Let's enhance the demo program with a ToolBar containing the same commands. Again, we just need to reference the command properties using their qualified names. Add the following ToolBar and buttons beneath the XAML for the menu:

<ToolBar DockPanel.Dock="Top" FontFamily="Wingdings" FontSize="16px">
    <Button Command="ApplicationCommands.Cut">"</Button>
    <Button Command="ApplicationCommands.Copy">4</Button>
    <Button Command="ApplicationCommands.Paste">@</Button>
</ToolBar>

Run the program again to see the results. This time the text of the commands is ignored because we are using specific characters as button content. However, the commands still work in the same way and the buttons are automatically enabled and disabled according to the availability of the commands.

WPF basic commanding with menu and toolbar

10 June 2015