CommandManager.AddCanExecuteHandler 方法

定义

将指定的 CanExecuteRoutedEventHandler 附加到指定的元素。

public:
 static void AddCanExecuteHandler(System::Windows::UIElement ^ element, System::Windows::Input::CanExecuteRoutedEventHandler ^ handler);
public static void AddCanExecuteHandler (System.Windows.UIElement element, System.Windows.Input.CanExecuteRoutedEventHandler handler);
static member AddCanExecuteHandler : System.Windows.UIElement * System.Windows.Input.CanExecuteRoutedEventHandler -> unit
Public Shared Sub AddCanExecuteHandler (element As UIElement, handler As CanExecuteRoutedEventHandler)

参数

element
UIElement

要向其附加 handler 的元素。

handler
CanExecuteRoutedEventHandler

可以执行的处理程序。

例外

elementhandlernull

示例

以下示例创建 CanExecuteRoutedEventHandler 和 , ExecutedRoutedEventHandler 并将其附加到 Button 作为命令源的 Help

首先, Button 创建 并与 命令关联 Help

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

接下来,创建 CanExecuteRoutedEventHandlerExecutedRoutedEventHandler

private void HelpCmdExecuted(object sender, ExecutedRoutedEventArgs e)
{
    // OpenHelpFile opens the help file
    OpenHelpFile();
}
Private Sub HelpCmdExecuted(ByVal sender As Object, ByVal e As ExecutedRoutedEventArgs)
    ' OpenHelpFile opens the help file
    OpenHelpFile()
End Sub
private void HelpCmdCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
    // HelpFilesExists() determines if the help file exists
    if (HelpFileExists() == true)
    {
        e.CanExecute = true;
    }
    else
    {
        e.CanExecute = false;
    }
}
Private Sub HelpCmdCanExecute(ByVal sender As Object, ByVal e As CanExecuteRoutedEventArgs)
    ' HelpFilesExists() determines if the help file exists
    If HelpFileExists() = True Then
        e.CanExecute = True
    Else
        e.CanExecute = False
    End If
End Sub

最后,使用 AddCanExecuteHandlerAddExecutedHandler将处理程序附加到 Button

CommandManager.AddExecutedHandler(helpButton, HelpCmdExecuted);
CommandManager.AddCanExecuteHandler(helpButton, HelpCmdCanExecute);
CommandManager.AddExecutedHandler(helpButton, AddressOf HelpCmdExecuted)
CommandManager.AddCanExecuteHandler(helpButton, AddressOf HelpCmdCanExecute)

适用于

另请参阅