CommandManager.RequerySuggested 如何工作? [英] How does CommandManager.RequerySuggested work?

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

问题描述

MSDN 仅声明

在 CommandManager 检测到可能改变命令执行能力的条件时发生.

但是我似乎找不到任何关于它是如何工作的痕迹,我应该注意/避免什么等等......它只是监听输入吗?(即:鼠标移动、按键按下等)

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()中的限制检查 是使用旧值完成的.因此,尽管实际达到了限制,该按钮仍保持启用状态.有趣的是,在您单击 UI 中的任意位置后,该按钮现在被禁用,因为 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 方法在我收到异步操作的结果后立即出现在我的 ViewModel 中.
更新: 请注意,此方法必须在UI线程上调用,否则无效!(感谢 midspace 的评论)

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 如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆