Logging Routed Commands

This blog post shows how to log details about any routed command being executed in a Window. The technique only works with routed commands because it depends on the CommandManager’s tunneling PreviewExecuted attached event to notify the Window of command execution.

Suppose you have a Window with many controls in it and you want to figure out when any routed commands are executed, perhaps for debugging or usage analysis purposes. How might one do that?

The technique I came up with depends on the CommandManager class to notify the Window whenever a routed command in that Window is executed. I establish a listener on CommandManager’s attached PreviewExecuted event and let that tell me everything I need to know.

Here’s the Window’s code-behind:

Command Logging (code)

Here’s the XAML, which contains a few Buttons with their Command property set:

Command Logging (xaml)

After I run the application and click each Button once, the log file (which is really just text in the Output window in VS) contains this:

Command Executed @ 10/25/2007 7:38:00 PM
  Name=Open; Parameter=; Source=System.Windows.Controls.Button: Open Sesame!
Command Executed @ 10/25/2007 7:38:01 PM
  Name=Close; Parameter=; Source=System.Windows.Controls.Button: Close Sesame!
Command Executed @ 10/25/2007 7:38:02 PM
  Name=My Routed Command; Parameter=fooParam; Source=System.Windows.Controls.Button: My Routed Command!

Notice that the “My Normal Command!” Button’s command does not appear in the log. That is because the MyCmd command is not a routed command, but simply a class which implements ICommand. Only the execution of RoutedCommand objects are logged.

Download the source code here: Command Logging (demo app) Be sure to change the file extension from .DOC to .ZIP and then decompress the file.


One Response to Logging Routed Commands

  1. […] Routed Commands in F# In my previous post I showed how to set up a generic technique for logging details about the execution of routed […]

%d bloggers like this: