Skip navigation

The RoutedCommand doesn’t quite make sense to me in the M-V-VM pattern. Why go through the effort of creating command bindings when you are holding an instance of the Command within your controller (or ViewModel). Just trust me when I say it’s convoluted.

At the other extreme, you would have to create a new class for each and every Command that your application provides. While there is a benefit to this scenario in some cases, in most instances it’s overkill. A happy medium is having a class that implements ICommand and exposes events for CanExecute and Execute. Hence I give you the DelegatingCommand.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;

namespace YourNamespaceHere
{
    /// <summary>
    /// Delegate for adding logic for determining if a 
    /// <see cref="DelegatingCommand"/> can be executed
    /// </summary>
    /// <param name="parameter">
    /// The parameter being passed to the command (can be null)
    /// </param>
    /// <returns>
    /// True if the command can be executed with the given parameter
    /// </returns>
    public delegate bool CanExecuteHandler(object parameter);

    /// <summary>
    /// Delegate for adding logic to execute a <see cref="DelegatingCommand"/>
    /// </summary>
    /// <param name="parameter">
    /// The parameter being passed to the command (can be null)
    /// </param>
    public delegate void ExecuteHandler(object parameter);

    /// <summary>
    /// The DelegatingCommand provides an implementation of <see cref="ICommand"/>
    /// that can delegate CanExecute and Execute calls to listeners. As opposed
    /// to the RoutedCommand, it does not require any custom wiring to the UI,
    /// just bind an instance to any <see cref="ICommand"/> (e.g.
    /// <see cref="Button"/> or <see cref="MenuItem"/>) using XAML. This is 
    /// useful when implementing the MVC pattern within WPF. The Controller can
    /// expose a DelegatingCommand as a property and the View can bind to it.
    /// Anyone aware of the instance can handle the CanExecuteRequested and/or
    /// ExecuteRequested events.
    /// </summary>
    public class DelegatingCommand : ICommand
    {
        public event CanExecuteHandler CanExecuteRequested;
        public event ExecuteHandler ExecuteRequested;

        public bool CanExecute(object parameter)
        {
            if (CanExecuteRequested != null)
                return CanExecuteRequested(parameter);
            return true;
        }

        private Object _Owner;
        public Object Owner
        {
            get { return _Owner; }
            set { _Owner = value; }
        }

        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            if (ExecuteRequested != null)
                ExecuteRequested(parameter);
        }

    }

}

7 Comments

  1. I too struggled with the concept of the "CommandModel" in M-V-VM.  I even blogged about a CommandModel very similar to your DelegatingCommand but based on the RoutedCommand.  I soon realized this was a pain in the behind, and revised it to be based solely on ICommand, making it nearly identical to your DelegatingCommand.  In the end, though, I determined there was too much functionality in a RoutedCommand that you usually can\’t do with out.  Specifically, the ability to map gestures to commands.  The way I do things now isn\’t exactly ideal, because my ViewModel has some dependence on the View (I create the bindings in the ViewModel\’s constructor, which means the constructor takes a Window or other UI element as a parameter).  It\’s still possible to code your ViewModel to be testable when there is no UI, one of the major benefits of this pattern, but it takes some discipline since you\’ve exposed the UI to the ViewModel.  I\’m still contemplating the design trade offs and alternative implementations here.

  2. That is how I was handling it before as well…my ViewModel was setting up the ClassCommandBinding and this tied my ViewModel to a specific View (or a Subclass of a specific view) I didn\’t even think about gestures and the like. I\’ll look to see what it would take to put gesture support in here…of course, since it\’s not actually hooked into the visual model, it would be difficult. Maybe some attached properties would be in order to allow it to do so.

  3. In the code from my blog, there\’s no tight coupling to a specific view.  The coupling is to a generic base.  This still isn\’t ideal, I absolutely agree.  What would be ideal would be a clean way to create the bindings within the XAML.  The original code attempted to do this through an attached property, but I did not find it to be clean by any stretch. 😦
     
    I\’m hopeful that some bright minds can work this one out, but for now I\’m sticking with what\’s simple, even if the coupling is wrong.

  4. Hi Brownie maybe there away to implement your delegate command so overcome my problem :
    Check this simple sample and his goal.
     
    http://forums.microsoft.com/MSDN/showpost.aspx?postid=2267526&siteid=1
     
    Happy if you add me as your messenger buddy.
     
    Gai.dvi@gmail.com
     
     
     

  5. Your DelegatingCommand class sounds perfect (I was about to try to create something similar for the same purpose when I saw this blog).  However I\’m unclear how to use the class.  Do you have an example of its use?

  6. Hi Brownie & William ,
    As I read in your blogs, you are big supporters of this Delegating Command idea =))
     
    I\’ve been keeping myself busy with all MVVM, CommandModel stuffs too and have read your posts above and in William\’s blog. One problem I see in your DelegatingCommand is that when we use ICommand instead of RoutedCommand, WPF doesnt automatically call CanExecute() on a frequent basis to check the enable status of a command.
     
    In my observation, CanExecute() is only called just before Execute() is called (for example when a button bound to that command is clicked) but not automatically.
     
    I also noticed that John Gossman – the father of MVVM also used a so-called "DelegateCommand" in one of his examples
    http://blogs.msdn.com/johngossman/archive/2008/05/16/attachedbehavior-pattern-sample.aspx
     
    What are your opinions?
     
     
     
     
     
     
     
     

  7. Hello,
       I haven\’t seen this issue that you mention regarding CanExecute() not being polled. For me it gets called whenever the UI changes. The DelegateCommand pattern did make it into the upcoming PRISM framework (John Gossman is a member of the PRISM team) from the Patterns and Practices team.


Leave a reply to Unknown Cancel reply