× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

CommandPattern with WPF

Gayot Fow
Feb 05, 2015
<p>An implementation of the Command Pattern would look like this...</p> <pre><code> &lt;Menu DockPanel.Dock="Top"&gt; &lt;MenuItem Header="file" Command="{Binding FileCommand}"/&gt; &lt;/Menu&gt; </code></pre> <p>...which declares an item bound to a command. The command would exist in the View Model with a declaration like this...</p> <pre><code> public ICommand FileCommand { get; set; } </code></pre> <p>... where ICommand is declared as an interface in the System.Windows.Input name space. <a href="http://msdn.microsoft.com/en-us/library/system.windows.input.icommand.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/system.windows.input.icommand.aspx</a></p> <p>To initialize the ICommand...</p> <pre><code>FileCommand = new RelayCommand(FileCommandExecute, FileCommandCanExecute); </code></pre> <p>...where 'RelayCommand' is a class explained in Josh Smith's seminal article on MVVM which is found here: <a href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/magazine/dd419663.aspx</a> Other implementations exist, like Prism's 'DelegateCommand'. The two delegates in the constructor are coded like this...</p> <pre><code> #region FileCommand callbacks private bool FileCommandCanExecute(object obj) { return true; } private void FileCommandExecute(object obj) { OpenFile(); } #endregion // end of FileCommand callbacks </code></pre> <p>...where the 'CanExecute' method enables or disables the command on the user surface depending upon the View Model's state. And the 'Execute' method performs the actual work. </p> <p>This example is a classical MVVM implementation of the command pattern. In your parlance, the View Model implementing the command is the 'receiver' and the View containing the menu is the 'invoker'. More recent implementations of the command pattern have been introduced such as the 'CompositeCommand' and 'Attached Behaviour', but these are outside the scope of your question. </p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/18355819/CommandPattern%20with%20WPF/18356244">Stack Overflow</a>.</p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus