本文介绍了CommandManager.RequerySuggested如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MSDN仅声明

但是我似乎找不到任何有关此工作原理的痕迹,我应该了解/避免的事情...它只是在听输入吗? (即:鼠标移动,按键按下等)

However I can't seem to find any traces of how this works, what I should be aware of / avoid etc...Does it just listen for input? (i.e.: mouse moves, keys pressed and so on)

推荐答案

我无法确切地告诉您CommandManager侦听的事件.但是,我可以告诉您,将CommandManager与异步操作结合使用时,您应该要小心.在ICommand实现中使用CommandManager时遇到以下问题:

I cannot tell you exactly what events the CommandManager listens to. However, I can tell you that you should be careful when using the CommandManager in connection with asynchronous operations. I had the following problem when I used the CommandManager in my ICommand implementations:

我有一个绑定到ICommand的按钮,该按钮触发了一个异步操作,该操作增加了一个值.现在,如果值已达到某个限制,则应该禁用按钮/ICommand(即其CanExecute()方法应返回false).问题是:CommandManager在单击按钮并启动异步操作之后立即调用了我的CanExecute()方法.此异步操作花了很长时间,但是它足够长的时间才能在CommandManager的检查之后 得到结果,因此CanExecute()中的极限检查是使用旧值完成的.因此,尽管实际上已达到限制,但该按钮保持启用状态.有趣的是,在用户界面中单击任意位置后,该按钮现在被禁用,因为CommandManager再次检查了ICommand,现在又对照限制检查了新值.实际上,我认为CommandManager在单击按钮后等待了约50毫秒,直到它执行了ICommand的检查,但我对此不太确定.

I had a button bound to an ICommand which triggered an asynchronous operation which increased a value. Now, the button/ICommand should be disabled (i.e. its CanExecute() method should return false) if the value had reached a certain limit. The problem was: The CommandManager called my CanExecute() method right after the button had been clicked and the asynchronous operation had been started. This asynchronous operation did not take long, but it was long enough to get its result after the CommandManager's check, so that the limit check in CanExecute() was done using the old value. Therefore, the button remained enabled although the limit was actually reached. The funny thing was, after you clicked anywhere in the UI, the button now got disabled because the CommandManager checked the ICommand once again and now the new value was checked against the limit.Actually, I think the CommandManager waited around 50ms after the button click until it performed the check of the ICommand, but I am not quite sure about that.

我的解决方案是通过调用 CommandManager.InvalidateRequerySuggested 方法就出现了.
更新:请注意必须在UI线程上调用此方法,否则它将无效! (感谢中部空间的评论)

My solution was to force the CommandManager to check the ICommand again by calling the CommandManager.InvalidateRequerySuggested method in my ViewModel right after I received the result of the async operation.
Update: Please note that this method must be called on the UI thread, otherwise it will have no effect! (Thanks to midspace for this comment)

这篇关于CommandManager.RequerySuggested如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 23:43