views:

138

answers:

1

I've been unable to find any info on this, which seems like it could be the only way to solve a past unanswered question of mine on SO. However, I think this should really be a separate question now.

I am wondering if there is a way to dynamically redefine an ICommand-derived class's CanExecute method. I'm still new to .NET and perhaps this is really obvious, but I haven't been able to figure it out. Has anyone here done this sort of thing before? If I could get this working, it would be very useful for my particular problem. Basically, I want to be able to loop over a List of ICommands and force all of their CanExecute methods to return true by replacing their implementation with a different one.

From searching for things like ".NET code replacement", I found this article, but I was hoping that there's a slightly simpler approach. However, if I have to, I'll do it.

+2  A: 

Have your ICommand derived class call a delegate to determine if CanExecute can be done, this way you can expose a setter for the delegate and change it at runtime

As a simple example:

public class MyCommand : ICommand
{
  private Func<object, bool> _canExecuteMethod;

  public void SetCanExecuteMethod(Func<object, bool> canExecuteMethod)
  {
    //check delegate not null if need be
    _canExecuteMethod = canExecuteMethod;
  }

  public bool CanExecute(object parameter)
  {
    //check for null delegate - maybe return false if it's null....
    return _canExecuteMethod(parameter);
  }

  //....other codefor ICommand

}

You could also utilize just Func<bool> for the delegate if you don't need the extra data to make the decision. Also the delegate can be exposed elsewhere if required and just called from the ICommand class

saret
thanks, I think this is a solid candidate. I'll give it a try.
Dave