I've done some WPF programing and one thing I never got was the command pattern. Every example seems to be for built in ones, edit, cut, paste. Anyone have an example or suggestion of best practice for custom commands?

+27  A: 

Ah ha! A question I can answer! Firstly, I should mention that I have personally found it easier to define and hook up commands in code rather than in XAML. It allows me to hook up the handlers for the commands a little more flexibly than an all XAML approach does.

You should work out what commands you want to have and what they relate to. In my application, I currently have a class for defining important application commands like so:

public static class CommandBank
  /// Command definition for Closing a window
  public static RoutedUICommand CloseWindow { get; private set; }

  /// Static private constructor, sets up all application wide commands.
  static CommandBank()
    CloseWindow = new RoutedUICommand();
    CloseWindow.InputGestures.Add(new KeyGesture(Key.F4, ModifierKeys.Alt));
    // ...

Now, because I wanted to keep the code all together, using a code only approach to Commands lets me put the following methods in the class above:

/// Closes the window provided as a parameter
public static void CloseWindowExecute(object sender, ExecutedRoutedEventArgs e)

/// Allows a Command to execute if the CommandParameter is not a null value
public static void CanExecuteIfParameterIsNotNull(object sender, CanExecuteRoutedEventArgs e)
  e.CanExecute = e.Parameter != null;
  e.Handled = true;

The second method there can even be shared with other Commands without me having to repeat it all over the place.

Once you have defined the commands like this, you can add them to any piece of UI. In the following, once the Window has Loaded, I add command bindings to both the Window and MenuItem and then add an input binding to the Window using a loop to do this for all command bindings. The parameter that is passed is the Window its self so the code above knows what Window to try and close.

public partial class SimpleWindow : Window
  private void WindowLoaded(object sender, RoutedEventArgs e)
    // ...
      new CommandBinding(

    foreach (CommandBinding binding in this.CommandBindings)
       RoutedCommand command = (RoutedCommand)binding.Command;
       if (command.InputGestures.Count > 0)
         foreach (InputGesture gesture in command.InputGestures)
           var iBind = new InputBinding(command, gesture);
           iBind.CommandParameter = this;

    // menuItemExit is defined in XAML
    menuItemExit.Command = CommandBank.CloseWindow;
    menuItemExit.CommandParameter = this;
    // ...

  // ....

I then also later have event handlers for the WindowClosing and WindowClosed events, I do recommend you make the actual implementation of commands as small and generic as possible. As in this case, I didn't try to put code that tries to stop the Window closing if there is unsaved data, I kept that code firmly inside the WindowClosing event.

Let me know if you have any follow up questions. :)

Your CanExecuteIfParameterIsNotNull contains one of my pet annoyances.Why not just e.CanExecute = e.Parameter != null;
@Ray That was not something I was aware I could do! Thanks for the edit Drew. :)

Thanks! I had only been doing things in xaml and I just never "Got" it, that helps a lot.

Brian Leahy
This is not an answer. Use a comment or edit the question.
Geoffrey Chetwood
Comments didnt exist when this was posted
Brian Leahy
But comments exist now.
+3  A: 

The thing about XAML is that it is fine for 'simple' programs, but sadly, it doesn't work well when you want to do things like share functions. Say you have several classes and UI's all of which had commands that were never disabled, you'd have to write a 'CanAlwaysExecute' method for each Window or UserControl! That's just not very DRY.

Having read several blogs and through trying several things, I've made the choice to make XAML purely about looks, styles, animation and triggers. All my hooking up of event handlers and commanding is now down in the code-behind. :)

Another gotcha by the way is Input binding, in order for them to be caught, focus must be on the object that contains the Input bindings. For example, to have a short cut you can use at any time (say, F1 to open help), that input binding must be set on the Window object, since that always has focus when your app is Active. Using the code method should make that easier, even when you start using UserControls which might want to add input bindings to their parent Window.

+4  A: 

In the September 2008 edition of the MSDN magazine, Brian Noyes has a excellent article about the RoutedCommand/RoutedEvents!!!

Here is the link: http://msdn.microsoft.com/en-us/magazine/cc785480.aspx