【问题标题】:Executed gets not called after PreviewExecutedPreviewExecuted 后未调用 Executed
【发布时间】:2015-05-08 12:23:29
【问题描述】:

这是我的代码:

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。

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

【问题讨论】:

  • 可能是其他地方的代码得到了事件(通过隧道)并处理了它。
  • 基本没有。即使在只有一个按钮和上面代码的全新简约示例项目中也会发生这种行为。

标签: c# wpf routed-commands


【解决方案1】:

您将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.Handled 在预览事件之后是false,则应该引发Executed 事件。但在调用PreviewExecuted 处理程序后它永远不会为假(CommandBindings.cs,OnExecuted):

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

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

为什么会这样,我不知道。 PreviewCanExecute 的工作方式相同,但它仅在 e.CanExecute 设置为 true 时将 e.Handled 设置为 true - 如果您在预览处理程序中执行此操作,则不会调用 CanExecute 处理程序,无论 e.Handled .

我的假设是“如果预览事件未处理”是“如果预览事件没有注册的处理程序”。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-25
  • 1970-01-01
  • 2020-07-20
  • 2020-07-04
  • 1970-01-01
  • 2018-12-09
相关资源
最近更新 更多