开发者

Need help understanding MVVM Tutorial, RelayCommand & Use of lambdas

I am reading Josh Smith' WPF Apps With The Model-View-ViewModel Design Pattern tutorial

i don't understand what the below code is trying to do.

First, the syntax reminds me proper开发者_如何学JAVAties, but with add/remove instead.

But what is CommandManager.RequerySuggested?

It delegates the event subscription to the CommandManager.RequerySuggested event. This ensures that the WPF commanding infrastructure asks all RelayCommand objects if they can execute whenever it asks the built-in commands

//Figure 3 The RelayCommand Class
public class RelayCommand : ICommand 
{ 
#region Fields 
    readonly Action<object> _execute; 
    readonly Predicate<object> _canExecute; 
#endregion // Fields
#region Constructors 
public RelayCommand(Action<object> execute) : this(execute, null) 
{ } 
public RelayCommand(Action<object> execute, Predicate<object> canExecute) 
{ 
    if (execute == null) throw new ArgumentNullException("execute"); 
   _execute = execute; 
   _canExecute = canExecute; 
} 
#endregion // Constructors 
#region ICommand Members 
[DebuggerStepThrough] 
public bool CanExecute(object parameter) 
{ 
    return _canExecute == null ? true : _canExecute(parameter); 
} 
public event EventHandler CanExecuteChanged 
{ 
    add    { CommandManager.RequerySuggested += value; } 
    remove { CommandManager.RequerySuggested -= value; } 
} 
public void Execute(object parameter) 
{ _execute(parameter); } 
#endregion // ICommand Members }

Also, save command is configured with lambdas. 1st, there are 2 param variables. Will they conflict? i cannot just do something like RelayCommand(this.Save(), this.CanSave) or is there no such syntax.

_saveCommand = new RelayCommand(param => this.Save(),
                                param => this.CanSave );


  1. CommandManager.RequerySuggested += value means that if the function for CanExecute can resolve to both true and false depending on some conditions.

    WPF will disable the Button/MenuItem (CommandButtonBase) if it evaluates to false and enable whenever the condition evaluates to true.
    If you don't have those two lines, WPF will ask the command only once (when the Button/MenuItem is loaded and will not update after that unless you do it manually.

  2. The two parameters (lambda-expressions) are of type Action<object> and a Predicate<object> respectively. So, they cannot, by definition, conflict (params is just a name - and as the two functions have different scope - they don't conflict).

    If you have a method with the right signature, you can use that in the constructor

    • private void Save(object obj)
      and
      private bool CanSave(object obj)

    respectively, but you shouldn't have the () at the end - so new RelayCommand(this.Save,this.CanSave) should work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜