user3143810
user3143810

Reputation:

Binding commands without PRISM

Since I started using MVVM, I've always used PRISM's DelegateCommand class for binding commands in my view models to button commands in my views. I believe Telerik also has an equivalent of DelegateCommand.

My question is, is there a built in alternative to using 3rd party frameworks such as prism and telerik. If I'm throwing together a quick throwaway application I may not want the hassle of installing packages from NuGet. Is there a way to achieve the same thing using a Func or an Action or a delegate?

Upvotes: 1

Views: 796

Answers (1)

BradleyDotNET
BradleyDotNET

Reputation: 61349

No, you still need a Command class that implements ICommand. However, you can write your own DelegateCommand really easily (citation, I wrote this off the top of my head in less than a minute):

public class DelegateCommand : ICommand
{
     private Action<object> execute;

     public DelegateCommand(Action<object> executeMethod)
     {
          execute = executeMethod;
     }

     public bool CanExecute(object param)
     {
         return true;
     }

     public void Execute(object param)
     {
         if (execute != null)
             execute(param);
     }
}

Use and enjoy! You could take an additional Func<bool, object> parameter if you wanted custom CanExecute behavior instead of returning true.

Note, if you really don't like null as the function, and want it to throw if you try it, just use this constructor instead:

     public DelegateCommand(Action<object> executeMethod)
     {
          if (executeMethod == null)
              throw new ArgumentNullException("executeMethod");

          execute = executeMethod;
     }

Upvotes: 1

Related Questions