CommandManager.AddCanExecuteHandler Method

Definition

Attaches the specified CanExecuteRoutedEventHandler to the specified element.

C#
public static void AddCanExecuteHandler(System.Windows.UIElement element, System.Windows.Input.CanExecuteRoutedEventHandler handler);

Parameters

element
UIElement

The element to attach handler to.

handler
CanExecuteRoutedEventHandler

The can execute handler.

Exceptions

element or handler is null.

Examples

The following example creates a CanExecuteRoutedEventHandler and an ExecutedRoutedEventHandler and attaches them to a Button which is a command source for the Help command.

First, the Button is created and associated with the Help command.

XAML
<Button Command="ApplicationCommands.Help"
        Name="helpButton">Help</Button>

Next, the CanExecuteRoutedEventHandler and the ExecutedRoutedEventHandler are created.

C#
private void HelpCmdExecuted(object sender, ExecutedRoutedEventArgs e)
{
    // OpenHelpFile opens the help file
    OpenHelpFile();
}
C#
private void HelpCmdCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
    // HelpFilesExists() determines if the help file exists
    if (HelpFileExists())
    {
        e.CanExecute = true;
    }
    else
    {
        e.CanExecute = false;
    }
}

And finally, the handlers are attached to the Button using the AddCanExecuteHandler and AddExecutedHandler.

C#
CommandManager.AddExecutedHandler(helpButton, HelpCmdExecuted);
CommandManager.AddCanExecuteHandler(helpButton, HelpCmdCanExecute);

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, 10

See also