Introduction to the WPF Command Framework

Introduction to the WPF Command Framework

indows Presentation Foundation (WPF) not only lets you do new things, it lets you do familiar things in new ways. As we’re all developers, rather than going through the background information, this article just dives right in with an example and works from there. Here’s a simple user interface?a typical window with a ListBox and a menu (see Figure 1).

Figure 1. Typical Simple Window: Here’s a simple window example that contains a ListBox and a Delete menu.

In this example, you want to make sure that users have selected a customer from the list before they can click the Delete menu. How many times have you added this sort of code to one of your Windows applications?

   private void HandleMenus()   {      menuDelete.IsEnabled = lsbCustomers.SelectedItem != null;   }

The code disables the Delete menu based on whether a user has selected a Customer. Code such as this is a common approach to keep menus and buttons enabled or disabled at the right times. Usually, calls to this or similar methods are riddled throughout the user interface like this:

   private void lsbCustomers_SelectionChanged(object sender,        SelectionChangedEventArgs e)
Figure 2. More Complex Window: Adding a second list box to the window example complicates the UI code for enabling or disabling the Delete menu.
{ HandleMenus(); }

This is a venerable approach, but it can easily become convoluted as your UI becomes more complicated. For example, suppose the window has two list boxes (see Figure 2).

Even though this still isn’t a complicated window, simply adding one more list box requires even more conditional code to properly handle the enabling of the Delete menu.

   private void HandleMenus()   {      menuDelete.IsEnabled =          (lsbCustomers.SelectedItem != null &&          ((ListBoxItem)lsbCustomers.SelectedItem).IsFocused) ||         (lsbProducts.SelectedItem != null &&          ((ListBoxItem)lsbProducts.SelectedItem).IsFocused);                               }

It also requires additional code to determine which ListBox the delete operation should affect.

   private void menuDelete_Click(object sender, RoutedEventArgs e)   {      if (lsbCustomers.SelectedItem != null &&          ((ListBoxItem)lsbCustomers.SelectedItem).IsFocused)            lsbCustomers.Items.Remove(lsbCustomers.SelectedItem);      else if (lsbProducts.SelectedItem != null &&          ((ListBoxItem)lsbProducts.SelectedItem).IsFocused)            lsbProducts.Items.Remove(lsbProducts.SelectedItem);   }

Imagine a window with as few as five controls that support the Delete operation. The code necessary to wire up each one of those quickly becomes burdensome. This burden is exacerbated when more than one control can invoke the Delete operation. Fortunately, WPF provides a better approach. The WPF command framework simplifies the UI code required in situations like these because it separates commands from implementation, letting you bind controls to specific commands, as you’ll see next.

Enter WPF Commands
Here’s how you could hook up the first example (the single list box window) with WPF commands.

                                                                          Grissom       Brass       Sara       Warrick   

Notice that the preceding code assigns a value to the Command property of the Delete menu. It also adds a command binding to the customer ListBox. In this scenario, the Menu is the command source, and the ListBox acts as a command target. The CommandBinding specifies delegates for CanExecute and Executed. Here are their implementations:

   private void DeleteCustomer_CanExecute(      object sender, CanExecuteRoutedEventArgs e)   {      e.CanExecute = lsbCustomers.SelectedItem != null;   }      private void DeleteCustomer_Executed(object sender,       ExecutedRoutedEventArgs e)   {      lsbCustomers.Items.Remove(lsbCustomers.SelectedItem);   }

So far, the code doesn’t look all that different from the first example. However, the benefits of this approach become clearer when you add the second “Products” list box:

                               Widget     Whatsit     Something   

Again, you need only to implement the CanExecute and Executed methods, as shown below:

   private void DeleteProduct_CanExecute(object sender,       CanExecuteRoutedEventArgs e)   {      e.CanExecute = lsbProducts.SelectedItem != null;   }      private void DeleteProduct_Executed(object sender,       ExecutedRoutedEventArgs e)   {      lsbProducts.Items.Remove(lsbProducts.SelectedItem);   }   
Author’s Note: The CanExecute method gets called a lot?make it efficient!

Unlike the traditional approach, when using the WPF command approach, you don’t need to change the command source (the Delete menu) code to add the second list box.

Also note that you don’t have to consider which control has the focus in this implementation. The CommandManager (the class that coordinates WPF commands) interacts with the FocusManager to determine which control currently has the focus.

WPF Command Framework Basics
Keeping that brief example in hand, here’s some basic information about how the WPF command framework works.

Command Sources
A command source, such as a button or menu, invokes commands. Usually, command sources implement ICommandSource. You can also invoke commands declaratively, through InputBindings. With an InputBinding in place, when an InputGesture (such as Ctrl-C for copy) occurs, the framework invokes the associated command (such as, ApplicationCommands.Copy).

Built-In Commands
WPF controls are hooked up to some commands/input gestures out of the box. There are many of these built-in commands in the .NET framework. The first example used the ApplicationCommands.Delete command. Other built-in commands include Copy, Paste, and many more. These commands are made even handier because many of the WPF controls are aware of them. For example, you don’t have to do anything special to wire up Copy and Paste to a TextBox; the TextBox control already has the bindings built in, and automatically implements commands such as Copy and Paste.

No Automatic Implementation
However, WPF commands don’t implement command behavior. This is probably the most common misconception developers have when learning about WPF commands. WPF commands merely notify UI elements that a command has been invoked?the UI elements themselves must implement any desired behavior. This separation of command from behavior is a very powerful feature, as you can see in the preceding example, where the Delete command is invoked via the same source (the Delete menu), but has two completely different implementations.

Also, WPF commands do not automatically provide undo/redo capabilities; if you need those capabilities, you still have to implement them manually within your application. However, you can connect your code to the WPF Undo and Redo commands to cause the corresponding actions to occur.

Differences Between Routed Commands and Windows Events
Routed commands are commands that implement the ICommand interface, and are routed through the WPF element tree. The RoutedCommand class provides an implementation of this behavior. Windows events, on the other hand, are not routed. The traditional approach for responding to user action involves writing code in event handlers (such as Menu_Click). That approach requires the event-handling code to consider which control has the focus, as in the HandleMenus code shown earlier.

One of the advantages of using RoutedCommands is that the framework takes care of managing focus. When using RoutedCommands, you don’t need to write code to consider focus.

Despite their power, WPF Commands don’t solve all of your problems out of the box. For example, when editing formatted text, it is common to show the toggle status of bold, italic, underline, etc., as the user selects text. While this capability doesn’t exist as a first-class citizen in the framework, the community has come up with several approaches to solve the problem of communicating additional status back to menu items.

Custom Commands
Creating your own commands is both very useful and quite easy to do?you can use any class that implements the ICommand interface. However, the framework already includes the RoutedUICommand that implements the ICommand interface nicely, so you can usually use that instead. As an example, here’s how to add a command that represents inserting a customer.

   public static class MyCommands   {      static MyCommands()      {         InsertCustomer = new RoutedUICommand(            "Insert Customer", "InsertCustomer",             typeof(MyCommands));      }         public static RoutedUICommand InsertCustomer       {          get; private set;       }   }

Now add a menu item to the window:


Also, add a CommandBinding to the window:


And finally, add the implementation code:

      private void InsertCustomer_CanExecute(object sender,       CanExecuteRoutedEventArgs e)   {      e.CanExecute = true;   }      private void InsertCustomer_Executed(object sender,       ExecutedRoutedEventArgs e)   {      ListBoxItem item = new ListBoxItem();      item.Content = "New Customer";      lsbCustomers.Items.Add(item);   }   
Author’s Note: If the CanExecute status of a command changes outside of a change in focus (such as when an asynchronous operation completes), call CommandManager.InvalidateRequerySuggested.

The WPF Command Framework is a simple yet powerful framework that makes connecting menus and buttons to command implementations easy and helps keep your code organized.


About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist