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.
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
InsertCustomer = new RoutedUICommand(
"Insert Customer", "InsertCustomer",
public static RoutedUICommand InsertCustomer
get; private set;
Now add a menu item to the window:
Header="Insert Customer" />
Also, add a CommandBinding to the window:
And finally, add the implementation code:
private void InsertCustomer_CanExecute(object sender,
e.CanExecute = true;
private void InsertCustomer_Executed(object sender,
ListBoxItem item = new ListBoxItem();
item.Content = "New Customer";
|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.