C# PreviewExecuted后未调用Executed
这是我的密码:C# PreviewExecuted后未调用Executed,c#,wpf,routed-commands,C#,Wpf,Routed Commands,这是我的密码: var commandBinding = new CommandBinding(ApplicationCommand.New); commandBinding.PreviewExecuted += OnPreviewExecuted; commandBinding.Executed += OnExecuted; CommandBindings.Add(commandBinding); void OnPreviewExecuted(object sender, ExecutedR
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();
}
说明:“…如果未处理预览事件,则在命令目标上引发已执行事件。”
对于PreviewCanExecute事件,这确实可以正常工作。但在这种情况下,当PreviewExecuted事件正在侦听时,不会调用已执行事件
我没有在这个话题上找到任何东西,所以我想问一下,这个行为是故意的还是不正确的。似乎你设置的
e.Handled
并不重要
以下是决定引发哪些事件的代码(RoutedCommand.cs中的ExecuteImpl):
因此,如果在预览事件之后e.Handled
为false
,则应引发已执行的
事件。但在调用PreviewExecuted
处理程序(CommandBindings.cs,OnExecuted)后,它永远不会为false:
它只是在调用预览处理程序后将e.Handled
设置为true
为什么会这样,我不知道PreviewCanExecute
的工作方式相同,但只有当e.Handled
设置为true时,才会将e.CanExecute
设置为true-如果在预览处理程序中执行此操作,则无论e.Handled
如何,都不会调用CanExecute
处理程序
我的假设是,“如果预览事件未被处理”是“如果预览事件没有注册的处理程序”的一个不幸的措词,可能是其他地方的代码(通过隧道)得到了事件基本上没有。这种行为甚至发生在一个新的极简主义样本项目中,只有一个按钮和上面的代码。你完全正确。这里()是引用。我将询问一些microsoft员工“为什么”,另请参见,它确认
e.Handled
无效,并且在第一个处理程序(将是Preview*
)执行后,路由立即停止@斯蒂芬,有什么解释吗?
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);
}
...
}
PreviewExecuted(sender, e);
e.Handled = true;