在PreviewExecuted之后执行未被调用

时间:2015-05-08 12:23:29

标签: c# wpf routed-commands

这是我的代码:

var commandBinding = new CommandBinding(ApplicationCommand.New);
commandBinding.PreviewExecuted += OnPreviewExecuted;
commandBinding.Executed += OnExecuted;
CommandBindings.Add(commandBinding);

void OnPreviewExecuted(object sender, ExecutedRoutedEventArgs e) {
  e.Handled = false;
}

void OnExecuted(object sender, ExecutedRoutedEventArgs e) {
  DoSomething();
}

MSDN说:" ...如果未处理预览事件,则会在命令目标上引发Executed事件。"

这对PreviewCanExecute事件可以正常工作。但在这种情况下,当PreviewExecuted-Event正在侦听时,不会调用Executed-Event。

我没有找到关于这个主题的任何内容,所以我想问一下,这种行为是有意还是不正确。

1 个答案:

答案 0 :(得分:5)

似乎将e.Handled设置为“

”并不重要。

以下是决定要引发哪些事件的代码(RoutedCommand.cs中的ExecuteImpl):

ExecutedRoutedEventArgs args = new ExecutedRoutedEventArgs(this, parameter);
args.RoutedEvent = CommandManager.PreviewExecutedEvent;

if (targetUIElement != null)
{
    targetUIElement.RaiseEvent(args, userInitiated);
}
else
{
    ...
}

if (!args.Handled)
{
    args.RoutedEvent = CommandManager.ExecutedEvent;
    if (targetUIElement != null)
    {
        targetUIElement.RaiseEvent(args, userInitiated);
    }
    ...
}

的确,如果预览事件后e.Handledfalse,则应引发Executed事件。但是在调用PreviewExecuted处理程序后,它永远不会出错(CommandBindings.cs,OnExecuted):

PreviewExecuted(sender, e);
e.Handled = true;

在调用预览处理程序后,它只是将e.Handled设置为true ...

为什么会这样,我不知道。 PreviewCanExecute的工作方式相同,但如果e.Handled设置为true,则只会将e.CanExecute设置为true - 如果您在预览处理程序中执行此操作,CanExecute处理程序赢了&# 39;无论e.Handled如何都要被调用。

我的假设是" 如果未处理预览事件"是一个令人遗憾的措辞" 如果预览事件没有注册处理程序 "。