Building Custom Commands

Topics: Prism v2 - Silverlight 2, Prism v2 - WPF 3.5
Jan 28, 2009 at 8:51 AM
Edited Jan 28, 2009 at 8:52 AM
I want to extend the Composite WPF/SL command system using derived classes of DelegateCommand and CompositeCommand.

For the CompositeCommand it works fine: we can overload the virtual methods CanExecute()  and Execute().
For the DelegateCommand these methods are non-virtual and break the extensibility.

Is any reason for this?

Cheers,
Jani
Jan 28, 2009 at 1:00 PM

Hi Jani,

 

The reason the DelegateCommand methods are not virtual is that you can pass as delegates both the CanExecuteMethod and the ExecuteMethod, thus defining how they will be implemented.

Since the DelegateCommand class is a lightweight class that was created for this purpose only (having just a delegate for Execute and CanExecute), you might considering creating your own class that implements ICommand directly instead of trying to extend DelegateCommand.

 

Please let me know if this helps.

 

Damian Schenkelman

http://blogs.southworks.net/dschenkelman
Jan 28, 2009 at 1:36 PM
Hi Damian,

Thanks for your feedback.

I have already a custom implementation of ICommand. I want to use a derived DelegateCommand to build the bridge to my Command.
Something like this:

----------------------------------------------------------------------------------------
class LinkedDelegateCommand<T> : DelegateCommand<T>
{
  public LinkedDelegateCommand( Action<T> executeMethod, Func<T, bool> canExecuteMethod )
   : base( executeMethod, canExecuteMethod )
  {
    // null-check...
    this.link = link;
  }
 
  public override bool CanExecute<T>( object parameter )
 {
    return link.CanExecute( parameter );
  }

  public override void Execute<T>( object parameter )
 {
    link.Execute( parameter );
  }

  private readonly ICommand link;
}

----------------------------------------------------------------------------------------
class MyCommand : ICommand
{
   bool CanExecute(object parameter)
   {
    return true; // custom code
  }

  void Execute(object parameter)
  {
    // custom code
  }
}

----------------------------------------------------------------------------------------
usage:
...
MyCommand myCommand = new MyCommand();
DelegateCommand viewCommand = new LinkedDelegateCommand( myCommand.Execute, myCommand.CanExecute );
...

LinkedDelegateCommand would also be a lightweight class.

Cheers,
Jani

Jan 29, 2009 at 5:46 AM
Hi Damian,

I am using now this approach:
public class LinkedDelegateCommand : DelegateCommand<object>
{
    public LinkedDelegateCommand( ICommand link )
        : base( link.Execute, link.CanExecute )
    {
        this.link = link;
    }

    public ICommand Link
    {
        get { return link;  }
    }

    private readonly ICommand link;
}


usage:
...
ICommand command = new LinkedDelegateCommand( new MyCommand() );
...

Cheers,
Jani