Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
998 views
in Technique[技术] by (71.8m points)

wpf - What is the actual task of CanExecuteChanged and CommandManager.RequerySuggested?

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; }     
}

I can't understand two things:

  1. what does the CanExecuteChanged event do?
  2. what does the CommandManager.RequerySuggested do?

The above code is from the RelayCommand Class from here.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  1. CanExecuteChanged notifies any command sources (like a Button or MenuItem) that are bound to that ICommand that the value returned by CanExecute has changed. Command sources care about this because they generally need to update their status accordingly (eg. a Button will disable itself if CanExecute() returns false).
  2. The CommandManager.RequerySuggested event is raised whenever the CommandManager 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.

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.

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...