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);
  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, 
                         ExecutePrefix + methodName);
var canExecuteDelegate = Delegate.CreateDelegate(canExecuteType, 
                             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;
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.

comments powered by Disqus


.NET Insight

Sign up for our newsletter.

Terms and Privacy Policy consent

I agree to this site's Privacy Policy.

Upcoming Events