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.

comments powered by Disqus

Featured

  • Visual Studio 'Tea & Technology' Video Miniseries Starts Next Week

    The goal of the miniseries is to provide an insider's snapshot look at some of the people who contribute to shaping the Visual Studio IDE every day.

  • Microsoft Releases OpenJDK 21 Build for Java Jockeys

    Microsoft today announced its "Microsoft Build of OpenJDK 21," taking advantage of new features and functionality in Java 21.

  • 'Dev Home' Update Leads Developer Goodies in AI-Powered Windows 11 Update

    Along with today's new AI-powered Windows 11 update come new goodies for developers, including a new edition of Dev Home, a preview offering described as a "control center" providing coding-focused features and functionality.

  • Community Dev Gives VS Code Python Some YAPF

    The latest update to Python in Visual Studio Code includes a new extension for Python formatting that was contributed by a member of the open source community.

Subscribe on YouTube