private void InvokeCommandEventHandler(object sender, EventArgs e)
{
// Checks if the command that is to be invoked is null, if so nothing is done (if a binding target does not exist, then nothing should be done, just like in normal binding, otherwise an application that uses the command
// binding in design mode would crash)
if (this.CommandPath == null)
return;
// PropertyPath does not provide a public method to provide the value of the object it points to, so we have to get it indirectly via a binding
Binding binding = new Binding
{
Path = this.CommandPath,
Source = (sender as FrameworkElement).DataContext
};
FrameworkElement frameworkElement = new FrameworkElement();
BindingOperations.SetBinding(frameworkElement, FrameworkElement.TagProperty, binding);
object commandValue = frameworkElement.Tag;
BindingOperations.ClearBinding(frameworkElement, FrameworkElement.DataContextProperty);
// Converts the command value to the actual command, if the value is not a command, nothing is done, because if a binding target does not exist, nothing should be done
ICommand command = commandValue as ICommand;
if (command == null)
return;
// Checks if the commands should be passed to the command, if so then get the parameters, otherwise set the parameters to null
object parameter = null;
if (this.PassEventArgumentsToCommand)
parameter = e;
// Checks if the command can be executed, if not nothing is done
if (!command.CanExecute(parameter))
return;
// Executes the command
command.Execute(parameter);
}