WPF Commands Part 1: Basics


WPF has introduced to us developers a wide new range of concepts and useful features, one of which is the Command System. It is based on the infamous Command Pattern, with a slight twist. It’s basically utilizing the Command Pattern with routing facility, as termed by Microsoft as the Routed Command System. Examining this closely, it’s similar to the Routed Event system that is inherent in WPF, and they used it for sending Commands for the UI controls to trigger a certain behaviour.

In one of my previous projects using WinForms and Model-View-Presenter (MVP) pattern, we faced the challenge of implementing a TreeView that is capable of triggering certain behaviours at different TreeNode Presenters. One of the developers came up with a very interesting implementation of using the Command Pattern and a variation of the Visitor Pattern. It was complicated, being a fresh developer, it took me hours to understand. Later he told me this pattern he used is known as the Double Dispatch pattern, which I later read about in a Design Pattern book. Now looking at Routed Command has reminded me of this, and is a similar implementation of the Double Dispatch.

It’s very interesting to see that Microsoft has started using a lot of Patterns in WPF, like Command and Observer. MS has also introduced a slight varation of the MVP, called Model-View-ViewModel pattern alongside the Pattern and Practices guide. In my opinion, this is a breath of fresh air, and .NET developers can no longer be “excused” from knowing about using and understanding patterns and how it helps to write elegant code, and decoupling your application.

Ok enough with the jibber jabber 🙂 Let’s look at some code.

This entry will go through a very simple use of WPF’s Routed Command system. There are two kinds of Commands in WPF, namely RoutedCommand and RoutedUICommand. As the name implies, the latter is used for UI purposes, and the former is not. For this entry we will be discussing the use of RoutedUICommands. In future posts, I will elaborate and show more examples of more advanced use of this.

WPF exposes a set of Command Libraries for us to use, namely ApplicationCommands, MediaCommands, ComponentCommands, NavigationCommands, and EditingCommands. In order to use these pre-built commands, you will require a UI control that implements ICommandSource. Examples are Buttons, Hyperlinks, MenuItems..etc. The good thing is that some of these controls internally are aware and can execute these commands, whereas some don’t. For instance, a TextBox inherently knows how to Cut, Copy, and Paste when we send the appropriate commands. Fortunately to customize controls to understand other commands is trivial as well, by making use of CommandBindings. When a command is fired and a CommandTarget is not specified, it bubbles up the visual tree and looks for a control that has a CommandBinding for that command, and attempts to execute it.

Let’s start with the first example. We will be hooking up Copy, Paste, Undo and Redo from ApplicationCommands to the Textboxes on the UI. Below is a screenshot of the UI. You can view a video of this sample here.

wpfcommand12Here’s a snipplet of the Xaml.

<StackPanel VerticalAlignment="Stretch" HorizontalAlignment="Stretch" >
 <Menu>
   <MenuItem Command="ApplicationCommands.Copy" />
   <MenuItem Command="ApplicationCommands.Paste" />
   <MenuItem Command="ApplicationCommands.Undo" />
   <MenuItem Command="ApplicationCommands.Redo" />
 </Menu>
 <Grid VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Margin="5" >
   <Grid.ColumnDefinitions>
     <ColumnDefinition Width="*" MaxWidth="100" MinWidth="75"/>
     <ColumnDefinition Width="2*" />
   </Grid.ColumnDefinitions>
   <Grid.RowDefinitions>
     <RowDefinition Height="*" />
     <RowDefinition Height="*" />
   </Grid.RowDefinitions>
 <Label Content="TextBox 1:" Target="{Binding ElementName=textbox1}" Grid.Column="0" Grid.Row="0"/>
 <Label Content="TextBox 2:" Target="{Binding ElementName=textbox2}" Grid.Column="0" Grid.Row="1"/>
 <TextBox Name="textbox1" Grid.Column="1" Grid.Row="0" />
 <TextBox Name="textbox2" Grid.Column="1" Grid.Row="1" />
 </Grid>
</StackPanel>

As you can see, the commands are hooked into the MenuItems on the StackPanel. Another very cool thing about commands is that they allow the controls to be enabled/disabled depending on the situation. Example, the Copy MenuItem will only be enabled if you highlight a text in the TextBox, otherwise it will be disabled, because there’s nothing to copy! How this works is via the ICommand interface, which all commands must implement. ICommand has two methods, CanExecute and Execute. CanExecute contains the logic of determining if the command can be executed, and Execute contains the logic of executing the intended behaviour. From the perspective of ApplicationCommand.Copy, CanExecute should only return true if a text is highlighted, and Execute will copy the selected text into clipboard.

Another cool thing is that these commands get applied on control that has Input Focus, without the need to explicitly binding the command to a control.This is functionality that is being built into TextBox and internally it knows how to execute a certain number of commands, like Copy, Paste and the usual suspects.

There’s no C# code needed, everything’s done in Xaml. All the boilerplate code’s been implemented for us, and we only need to specify what commands to use. In my later posts, I will attempt to go into futher detail on the RoutedCommand system.

You can download a copy of the solution here.

Share this post:
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: