RoutedCommand.CanExecute(Object, IInputElement) 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
确定此 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
。
- 属性
例外
target
不是 UIElement 或 ContentElement。
示例
以下示例是 CanExecuteChanged 自定义实现中的 ICommandSource事件处理程序。
this.Command
在此示例中为Command属性。ICommandSource 如果命令不是 null
,该命令将强制转换为 a RoutedCommand。 如果命令是一个 RoutedCommand,则 CanExecute 调用该方法传递 CommandTarget 和传递 CommandParameter。 如果命令不是, 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引发PreviewCanExecuteCanExecute通过元素树查找具有 a CommandBinding对象的隧道和气泡的事件。 如果找到一RoutedCommand个 CommandBinding for,则CanExecuteRoutedEventHandler调用附加到CommandBinding的项。 这些处理程序提供编程逻辑,用于确定是否可以 RoutedCommand 执行。
在 PreviewCanExecute .CommandTarget. 上引发事件和PreviewExecuted事件。 如果未设置,CommandTargetICommandSource则会PreviewCanExecute在具有键盘焦点的元素上引发事件CanExecute。