问题描述
我从Josh Smith的MVVM中获得了以下代码教程.
I got the following code from Josh Smith's MVVM tutorial.
任何人都可以快速解释一下此代码的实际作用吗?
Can anyone provide a quick explanation of what this code actually does?
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
我不明白两件事:
-
CanExecuteChanged
事件做什么? -
CommandManager.RequerySuggested
做什么?
- what does the
CanExecuteChanged
event do? - what does the
CommandManager.RequerySuggested
do?
上面的代码来自此处中的RelayCommand
类.. >
The above code is from the RelayCommand
Class from here.
推荐答案
-
CanExecuteChanged
通知绑定到该ICommand
的任何命令源(例如Button
或MenuItem
),由CanExecute
返回的值已更改.命令源对此很在意,因为它们通常需要相应地更新其状态(例如,如果CanExecute()
返回false
,则Button
将禁用自身). - 每当
CommandManager
认为某些变化会影响命令的执行能力时,就会引发CommandManager.RequerySuggested
事件.例如,这可能是焦点转移.事实证明,此事件引发了很多事情.
CanExecuteChanged
notifies any command sources (like aButton
orMenuItem
) that are bound to thatICommand
that the value returned byCanExecute
has changed. Command sources care about this because they generally need to update their status accordingly (eg. aButton
will disable itself ifCanExecute()
returnsfalse
).- The
CommandManager.RequerySuggested
event is raised whenever theCommandManager
thinks that something has changed that will affect the ability of commands to execute. This might be a change of focus, for example. Turns out that this event fires a lot.
因此,从本质上讲,这段代码的作用是确保每当命令管理器认为命令的执行能力已更改时,该命令将提高CanExecuteChanged
,即使它实际上并未更改.
So, in essence, what this bit of code does is ensure that whenever the command manager thinks a command's ability to execute has changed, the command will raise CanExecuteChanged
even if it hasn't actually changed.
我实际上不喜欢这种实现ICommand.CanExecuteChanged
的方法-感觉很懒,而且也不是完全可靠.我更喜欢一种更细粒度的方法,该命令公开一个方法(例如RaiseCanExecuteChanged()
),您可以调用该方法来引发CanExecuteChanged
,然后在适当的时候从视图模型中调用它.
I actually dislike this approach to implementing ICommand.CanExecuteChanged
- it feels lazy and isn't entirely reliable. I prefer a much more fine-grained approach where the command exposes a method (eg. RaiseCanExecuteChanged()
) you can call to raise CanExecuteChanged
, then you call this at the appropriate times from your view model.
例如,如果您有一个删除当前选定客户的命令,则它将有一个CanExecute()
处理程序,该处理程序仅在选择了一个客户的情况下才返回true
.因此,只要所选客户发生更改,您都将呼叫RaiseCanExecuteChanged
.
For example, if you have a command that deletes the currently selected customer, it would have a CanExecute()
handler that returns true
only if there is a customer selected. You would therefore call RaiseCanExecuteChanged
whenever the selected customer changes.
这篇关于CanExecuteChanged和CommandManager.RequerySuggested的实际任务是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!