<p>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?</p>

[{'answer_id': 8471, 'author': 'Nidonocu', 'author_id': 483, 'author_profile': 'https://Stackoverflow.com/users/483', 'pm_score': 6, 'selected': True, 'text': "<p>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.</p>\n\n<p>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:</p>\n\n<pre><code>public static class CommandBank\n{\n  /// Command definition for Closing a window\n  public static RoutedUICommand CloseWindow { get; private set; }\n\n  /// Static private constructor, sets up all application wide commands.\n  static CommandBank()\n  {\n    CloseWindow = new RoutedUICommand();\n    CloseWindow.InputGestures.Add(new KeyGesture(Key.F4, ModifierKeys.Alt));\n    // ...\n  }\n</code></pre>\n\n<p>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:</p>\n\n<pre><code>/// Closes the window provided as a parameter\npublic static void CloseWindowExecute(object sender, ExecutedRoutedEventArgs e)\n{\n  ((Window)e.Parameter).Close();\n}\n\n/// Allows a Command to execute if the CommandParameter is not a null value\npublic static void CanExecuteIfParameterIsNotNull(object sender, CanExecuteRoutedEventArgs e)\n{\n  e.CanExecute = e.Parameter != null;\n  e.Handled = true;\n}\n</code></pre>\n\n<p>The second method there can even be shared with other Commands without me having to repeat it all over the place.</p>\n\n<p>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.</p>\n\n<pre><code>public partial class SimpleWindow : Window\n{\n  private void WindowLoaded(object sender, RoutedEventArgs e)\n  {\n    // ...\n    this.CommandBindings.Add(\n      new CommandBinding(\n        CommandBank.CloseWindow,\n        CommandBank.CloseWindowExecute,\n        CommandBank.CanExecuteIfParameterIsNotNull));\n\n    foreach (CommandBinding binding in this.CommandBindings)\n    {\n       RoutedCommand command = (RoutedCommand)binding.Command;\n       if (command.InputGestures.Count &gt; 0)\n       {\n         foreach (InputGesture gesture in command.InputGestures)\n         {\n           var iBind = new InputBinding(command, gesture);\n           iBind.CommandParameter = this;\n           this.InputBindings.Add(iBind);\n         }\n       }\n    }\n\n    // menuItemExit is defined in XAML\n    menuItemExit.Command = CommandBank.CloseWindow;\n    menuItemExit.CommandParameter = this;\n    // ...\n  }\n\n  // ....\n}\n</code></pre>\n\n<p>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.</p>\n\n<p>Let me know if you have any follow up questions. :)</p>\n"}, {'answer_id': 8591, 'author': 'Nidonocu', 'author_id': 483, 'author_profile': 'https://Stackoverflow.com/users/483', 'pm_score': 2, 'selected': False, 'text': "<p>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 <em>DRY</em>.</p>\n\n<p>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. :)</p>\n\n<p>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.</p>\n"}, {'answer_id': 9239, 'author': 'Alan Le', 'author_id': 1133, 'author_profile': 'https://Stackoverflow.com/users/1133', 'pm_score': 3, 'selected': False, 'text': '<p>I blogged about a bunch of resources on WPF Commands along with an example last year at <a href="http://blogs.vertigo.com/personal/alanl/Blog/archive/2007/05/31/commands-in-wpf.aspx" rel="nofollow noreferrer">http://blogs.vertigo.com/personal/alanl/Blog/archive/2007/05/31/commands-in-wpf.aspx</a></p>\n\n<p>Pasting here:</p>\n\n<p><a href="http://www.informit.com/articles/article.aspx?p=688529&amp;seqNum=4" rel="nofollow noreferrer">Adam Nathan’s sample chapter on Important New Concepts in WPF: Commands</a></p>\n\n<p><a href="https://web.archive.org/web/20090202052155/http://www.microsoft.com/belux/msdn/nl/community/columns/jdruyts/wpf_commandpattern.mspx" rel="nofollow noreferrer">MSDN article: The Command Pattern In WPF</a></p>\n\n<p><a href="http://nayyeri.net/blog/how-to-add-commands-to-custom-wpf-control/" rel="nofollow noreferrer">Keyvan Nayyeri: How to Add Commands to Custom WPF Control</a></p>\n\n<p><a href="http://www.interact-sw.co.uk/iangblog/2005/05/19/avaloncommands" rel="nofollow noreferrer">Ian Griffiths: Avalon Input, Commands, and Handlers</a></p>\n\n<p><a href="http://en.wikipedia.org/wiki/Command_pattern" rel="nofollow noreferrer">Wikipedia: Command Pattern</a></p>\n\n<p><a href="https://msdn.microsoft.com/library/ms752308(v=vs.100).aspx" rel="nofollow noreferrer">MSDN Library: Commanding Overview</a></p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/system.windows.input.commandbinding.aspx" rel="nofollow noreferrer">MSDN Library: CommandBinding Class</a></p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/ms752051(VS.85).aspx" rel="nofollow noreferrer">MSDN Library: Input and Commands How-to Topics</a></p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/system.windows.documents.editingcommands.aspx" rel="nofollow noreferrer">MSDN Library: EditingCommands Class</a></p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/system.windows.input.mediacommands.aspx" rel="nofollow noreferrer">MSDN Library: MediaCommands Class</a></p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/system.windows.input.applicationcommands.aspx" rel="nofollow noreferrer">MSDN Library: ApplicationCommands Class</a></p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/system.windows.input.navigationcommands.aspx" rel="nofollow noreferrer">MSDN Library: NavigationCommands Class</a></p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/system.windows.input.componentcommands.aspx" rel="nofollow noreferrer">MSDN Library: ComponentCommands Class</a></p>\n\n<p>Also buried in the WPF SDK samples, there\'s a nice sample on RichTextBox editing which I\'ve extended. You can find it here: <a href="http://blogs.vertigosoftware.com/files/alan/richtexteditor.zip" rel="nofollow noreferrer">RichTextEditor.zip</a></p>\n'}, {'answer_id': 49275, 'author': 'rudigrobler', 'author_id': 5147, 'author_profile': 'https://Stackoverflow.com/users/5147', 'pm_score': 2, 'selected': False, 'text': '<p>In the September 2008 edition of the MSDN magazine, Brian Noyes has a excellent article about the RoutedCommand/RoutedEvents!!!</p>\n\n<p>Here is the link:\n<a href="http://msdn.microsoft.com/en-us/magazine/cc785480.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/magazine/cc785480.aspx</a></p>\n'}]
['https://Stackoverflow.com/questions/8452', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/580/']