RoutedCommand.Execute(Object, IInputElement) Method

Definition

Executes the RoutedCommand on the current command target.

C#
[System.Security.SecurityCritical]
public void Execute(object parameter, System.Windows.IInputElement target);
C#
public void Execute(object parameter, System.Windows.IInputElement target);

Parameters

parameter
Object

User defined parameter to be passed to the handler.

target
IInputElement

Element at which to begin looking for command handlers.

Attributes

Exceptions

Examples

The following example is from a custom implementation of ICommandSource sample.

this.Command in this example is the Command property on the ICommandSource. If the command is not null, the command is cast to a RoutedCommand. If it is a RoutedCommand, then the Execute method is called passing the CommandTarget and the CommandParameter. If the command is not a RoutedCommand, it is cast to an ICommand and the Execute method is called passing the CommandParameter.

C#
// If Command is defined, moving the slider will invoke the command;
// Otherwise, the slider will behave normally.
protected override void OnValueChanged(double oldValue, double newValue)
{
    base.OnValueChanged(oldValue, newValue);

    if (this.Command != null)
    {
        RoutedCommand command = Command as RoutedCommand;

        if (command != null)
        {
            command.Execute(CommandParameter, CommandTarget);
        }
        else
        {
            ((ICommand)Command).Execute(CommandParameter);
        }
    }
}

Remarks

The actual logic that executes the RoutedCommand is not contained in the Execute methods. Execute raises the PreviewExecuted and Executed events, which tunnel and bubble through the element tree looking for an object with a CommandBinding. If a CommandBinding for that RoutedCommand is found, then the ExecutedRoutedEventHandler attached to CommandBinding is called. These handlers supply the programming logic that performs the RoutedCommand.

The PreviewExecuted and Executed events are raised on the CommandTarget. If the CommandTarget is not set on the ICommandSource, the PreviewExecuted and Executed events are raised on the element with keyboard focus.

Applies to

Product Versions
.NET Framework 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9