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

  • Get Good at DevOps: Feature Flag Deployments with ASP.NET WebAPI

    They provide developers with the ability to toggle features on and off without having to redeploy code, making it easier to manage risk, test features in production, and facilitate smoother releases.

  • Implementing k-NN Classification Using C#

    Dr. James McCaffrey of Microsoft Research presents a full demo of k-nearest neighbors classification on mixed numeric and categorical data. Compared to other classification techniques, k-NN is easy to implement, supports numeric and categorical predictor variables, and is highly interpretable.

  • Building Secure and Scalable APIs in .NET 8

    Tony Champion: "From giving you access to the entire lifecycle of a request, the ability to configure and extend authentication and authorization, .NET 8 gives you the power to create APIs to meet even the most demanding needs."

  • What's New for Java Tooling in VS Code, Azure Cloud

    Java on Visual Studio Code gets a new tool to its extension pack, while Java on Azure upgraded the Azure Toolkit for IntelliJ and more in new regular updates for both properties.

Subscribe on YouTube