gpt4 book ai didi

c# - 需要帮助理解 MVVM 教程、RelayCommand 和 lambda 的使用

转载 作者:行者123 更新时间:2023-11-30 16:33:04 30 4
gpt4 key购买 nike

我正在阅读 Josh Smith 的 WPF Apps With The Model-View-ViewModel Design Pattern教程

我不明白下面的代码试图做什么。
首先,语法让我想起属性,但用添加/删除代替。

但是 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 }

此外,保存命令是用 lambda 表达式配置的。第一,有 2 个参数变量。他们会发生冲突吗?我不能只做类似 RelayCommand(this.Save(), this.CanSave) 的事情,或者没有这样的语法。

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

最佳答案

  1. CommandManager.RequerySuggested += value意味着如果 CanExecute 的函数可以同时解析为 truefalse取决于一些条件。

    WPF 将禁用 Button/MenuItem ( CommandButtonBase ) 如果计算结果为 false并在条件评估为 true 时启用.
    如果没有这两行,WPF 将只询问一次命令(当加载 Button/MenuItem 时,除非您手动执行,否则不会更新。

    <
  2. 两个参数(lambda 表达式)的类型为 Action<object>和一个 Predicate<object>分别。因此,根据定义,它们不能发生冲突( params 只是一个名称 - 由于这两个函数具有不同的范围 - 它们不会发生冲突)。

    如果你有一个带有正确签名的方法,你可以在构造函数中使用它

    • private void Save(object obj)

      private bool CanSave(object obj)

    分别,但你不应该有 ()最后 - 太新了RelayCommand(this.Save,this.CanSave)应该可以。

关于c# - 需要帮助理解 MVVM 教程、RelayCommand 和 lambda 的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3541913/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com