WPF provides a library of pre-defined commands (ApplicationCommands.Save, NavigationCommands.NextPage, etc.) that we can create command bindings for in our own application. I know that it is possible to create multiple command bindings for a single RoutedCommand/RoutedUICommand to obtain different behavior depending on the application context by specifying different executed handlers.
As I understand it, the purpose of the RoutedUICommand is largely to provide a common semantic reference. ApplicationCommands.New, to quote the MSDN documentation, "indicates the intention to create a new item." This command could be used in the command binding to create new items on several unrelated forms within an application.
I hardly ever see this sort of re-use being done. In code online and projects that I have worked on I generally see a RoutedCommand defined in the codebehind or viewmodel named something like 'NewEmailCommand'.
I see several advantages to re-using commands:
- RoutedUICommands generally have the Text property defined, so a menu item Header doesn't need to be defined.
- When the command has an input gesture defined, there isn't a need to specify an input binding every place that it is used.
- When the command has an input gesture defined, the InputGestureText in menu items is automatically populated.
- Using the same command promotes consistency across the application-- both in the labels used for the command and the key/mouse bindings.
A few possible disadvantages that come to mind:
- A command may be ambiguous in some situations. For instance: you may need two different 'New' commands in one spot (New->{Project..., Web Site...}).
- Instead or re-using a command, one might want to instead re-use a command binding that uses static handlers.
- ApplicationCommands.New is not a particularly informative command name; it does not tell you anything about the current command handler (such as what is getting created).
I am very much inclined to re-use commands, but as I said: I simply haven't seen it in practice.
What are your preferences? Are there any accepted 'best practices' that I haven't heard about? Are there glaring problems / other benefits to re-using commands?