Updated title: Why ICommand.CanExecute is getting called all the time, instead of working like an event?

China☆狼群 提交于 2019-12-03 15:51:12

In your CanExecuteDelegate you have hook to CommandManager.RequerySuggested.

So, whenever CommandManager.RequerySuggested is raised your CanExecuteDelegate will be called.

CommandManager.RequerySuggested event is raised whenever changes to the command source are detected by the command manager which ranges from Keyboard.KeyUpEvent, Mouse.ClickEvent etc.

Also, CommandManager has a static method - InvalidateRequerySuggested which forces the CommandManager to raise the RequerySuggestedEvent. So, you can call that to validate your commands too manually.

If you want to take the control in hand for raising CanExecute, you can use the Delegate Command provided by PRISM. CanExecute delegate will get called only when you explicitly call RaiseCanExecuteChanged() method exposed by Delegate Command.

Incorporating comments to answer

Breakpoint is hitting every time on turning to VS since CommandManager RequerySuggested event gets called on lost focus of window and on activation property changed of window. That's why you notice that breakpoint is hitting every now and then when you move to VS since focus moves from WPF window to Visual Studio.

When you set up your command, there's no reliable way for the runtime to know what data your CanExecute will rely on in order to make its decision. So, when you have commands that are bound into your UI and are registered in the CommandManager, the behaviour is that the CanExecute for all commands is re-evaluated whenever the state of your application changes. The way WPF knows about this is when a bound property is updated, or when a UI event occurs.

Typically you'll see CanExecute called whenever bindings update or when certain control events occur (for example, when a textbox's text is highlighted, the CanExecute of the inbuilt Cut and Copy commands will change, and so the highlight event triggers a re-evaluation that I would imagine is bound to the MouseUp event).

May be for unknown reason the UI could be getting updated (Measure, Arrange, and then Render calls). And if you have a breakpoint set on can execute method it'll be re-occurring. In other words you can't get pass this break point, each time you would do F5, the break point will it again.

To investigate you should put the logging/output statements in your can execute method and how many times and when it is getting called.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!