[英]CommandManager Executed Events don't fire for custom ICommands
The WPF CommandManager allows you to do the following (pseudo-ish-code): WPF CommandManager允许您执行以下操作(伪ish-code):
<Button Name="SomeButton" Command="{Binding Path=ViewModelCommand}"/>
And in the code-behind: 在代码隐藏中:
private void InitCommandEvents()
{
CommandManager.AddExecutedEventHandler(this.SomeButton, SomeEventHandler);
}
The SomeEventHandler
never gets called. SomeEventHandler
永远不会被调用。
To me this didn't seem like something very wrong to try and do, but if you consider what happens inside CommandManager.AddExecutedEventHandler
, it makes sense why it doesn't. 对我来说,尝试似乎并没有什么
CommandManager.AddExecutedEventHandler
,但是如果您考虑在CommandManager.AddExecutedEventHandler
内部发生了什么,那么为什么不这样做是有道理的。 Add to that the fact that the documentation clearly states that the CommandManager only works with RoutedCommands. 此外,文档明确指出CommandManager仅适用于RoutedCommands。
Nonetheless, this had me very frustrated for a while and led me to this question: 但是,这让我感到非常沮丧,并导致了我这个问题:
What would you suggest is the best workaround for the fact that the CommandManager does not support custom ICommands? 对于CommandManager不支持自定义ICommand的事实,您建议的最佳解决方法是什么? Especially if you want to add behavior around the execution of a command?
特别是如果您想在命令执行周围添加行为?
For now, I fire the command manually in code behind from the button click event. 现在,我在按钮单击事件后面的代码中手动触发命令。
I generally just subclass RoutedCommand and re-use its functionality instead of implementing an ICommand from scratch. 我通常只继承RoutedCommand并重新使用其功能,而不是从头开始实现ICommand。 Then it works well with CommandManager, etc, and everyone is happy.
然后,它可以与CommandManager等一起很好地工作,并且每个人都很高兴。
On the other hand, if you do implement an ICommand from scratch, it seems to me that there's no need of CommandManager.AddExecutedEventHandler: Your custom ICommand can easily expose its own way of registering for notifications when the command executes. 另一方面,如果您确实从头实现ICommand,在我看来,则不需要CommandManager.AddExecutedEventHandler:自定义ICommand可以在命令执行时轻松公开其自己的通知注册方式。 In fact, most custom ICommand implementations do this as the primary way of handling command execution.
实际上,大多数自定义ICommand实现将其作为处理命令执行的主要方式。
Either way it doesn't seem you would ever need both custom ICommand functionality and CommandManager support at the same time. 无论哪种方式,似乎都不会同时需要自定义ICommand功能和CommandManager支持。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.