RoutedCommand.CanExecute(Object, IInputElement) 方法

定義

判斷這個 RoutedCommand 是否能在其目前狀態中執行。

public:
 bool CanExecute(System::Object ^ parameter, System::Windows::IInputElement ^ target);
[System.Security.SecurityCritical]
public bool CanExecute (object parameter, System.Windows.IInputElement target);
public bool CanExecute (object parameter, System.Windows.IInputElement target);
[<System.Security.SecurityCritical>]
member this.CanExecute : obj * System.Windows.IInputElement -> bool
member this.CanExecute : obj * System.Windows.IInputElement -> bool
Public Function CanExecute (parameter As Object, target As IInputElement) As Boolean

參數

parameter
Object

使用者定義資料型別。

target
IInputElement

命令目標。

傳回

如果命令可以在目前命令目標上執行,則為 true,否則為 false

屬性

例外狀況

範例

下列範例是 CanExecuteChanged 的自定義實作中的 ICommandSource事件處理程式。

this.Command 在此範例中是 Command 上的 ICommandSource屬性。 如果命令不是 null,則命令會轉換成 RoutedCommand。 如果指令是 RoutedCommand,則 CanExecute 呼叫 方法會傳遞 CommandTargetCommandParameter。 如果指令不是 RoutedCommand,則會轉換成 ICommand ,並 CanExecute 呼叫 方法傳遞 CommandParameter

CanExecute如果方法傳true回 ,則會啟用控件,否則會停用控件。

private void CanExecuteChanged(object sender, EventArgs e)
{

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

        // If a RoutedCommand.
        if (command != null)
        {
            if (command.CanExecute(CommandParameter, CommandTarget))
            {
                this.IsEnabled = true;
            }
            else
            {
                this.IsEnabled = false;
            }
        }
        // If a not RoutedCommand.
        else
        {
            if (Command.CanExecute(CommandParameter))
            {
                this.IsEnabled = true;
            }
            else
            {
                this.IsEnabled = false;
            }
        }
    }
}
Private Sub CanExecuteChanged(ByVal sender As Object, ByVal e As EventArgs)

    If Me.Command IsNot Nothing Then
        Dim command As RoutedCommand = TryCast(Me.Command, RoutedCommand)

        ' If a RoutedCommand.
        If command IsNot Nothing Then
            If command.CanExecute(CommandParameter, CommandTarget) Then
                Me.IsEnabled = True
            Else
                Me.IsEnabled = False
            End If
            ' If a not RoutedCommand.
        Else
            If Me.Command.CanExecute(CommandParameter) Then
                Me.IsEnabled = True
            Else
                Me.IsEnabled = False
            End If
        End If
    End If
End Sub

備註

判斷是否可以在目前命令目標上執行的實際邏輯 RoutedCommand 不包含在 方法中 CanExecute ,而是 CanExecute 引發 PreviewCanExecute 和 事件,這些事件會 CanExecute 透過元素樹狀結構來擷取 具有的物件 CommandBinding。。 CommandBinding如果找到的 RoutedCommand ,則會CanExecuteRoutedEventHandler呼叫附加至 CommandBinding 的 。 這些處理程式提供程式設計邏輯,以判斷 是否可以 RoutedCommand 執行 。

PreviewCanExecutePreviewExecuted 事件會在 CommandTarget上引發。 CommandTarget如果未在 上ICommandSource設定 ,則會PreviewCanExecute在具有鍵盤焦點的 元素上引發 和 CanExecute 事件。

適用於