Using Aspect-Oriented Programming to Initialize and Connect WPF Commands: Listing 1.

Creating the DelegateCommand.

var mi = invocation.TargetType.GetMethod(ExecutePrefix + methodName,
          BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
var parameters = mi.GetParameters();

Type commandType;
Type canExecuteType;
Type delegateCommandType;
if (parameters.Length != 1)
{
  commandType = typeof(Action);
  canExecuteType = typeof(Func<bool>);
  delegateCommandType = typeof(DelegateCommand);
}
else
{
  var parameterType = parameters[0].ParameterType;
  commandType = typeof(Action<>).MakeGenericType(parameterType);
  canExecuteType = typeof(Predicate<>).MakeGenericType(parameterType);
  delegateCommandType = typeof(DelegateCommand<>).MakeGenericType(parameterType);
}

var commandDelegate = Delegate.CreateDelegate(commandType, 
                         invocation.InvocationTarget,
                         ExecutePrefix + methodName);
var canExecuteDelegate = Delegate.CreateDelegate(canExecuteType, 
                             invocation.InvocationTarget,
                             CanExecutePrefix + methodName, false, false);
var delegateCommand = Activator.CreateInstance(delegateCommandType,
                         canExecuteDelegate == null
                         ? new object[] { commandDelegate }
                         : new object[] { commandDelegate, canExecuteDelegate });
commands.Add(key, delegateCommand);
invocation.ReturnValue = delegateCommand;
return;
WPF Commands

About the Author

Patrick Steele is a senior .NET developer with Billhighway in Troy, Mich. A recognized expert on the Microsoft .NET Framework, he’s a former Microsoft MVP award winner and a presenter at conferences and user group meetings.