c# - 为什么 RelayCommands 通常使用惰性初始化?

标签 c# xaml mvvm data-binding lazy-initialization

使用 Josh Smith 的 RelayCommand 时,我见过的大多数示例都使用惰性初始化,例如:

public class ViewModel
{
    private ICommand myCommand;

    public ICommand MyCommand
    {
        get
        {
            if (myCommand == null)
            {
                myCommand = new RelayCommand(p => DoSomething() );
            }

            return myCommand;
        }
    }
    // ... stuff ...

}

而不是像这样在构造函数中创建 RelayCommand:

public class ViewModel
{
    public ViewModel()
    {
            MyCommand = new RelayCommand(p => DoSomething());
    }

    public ICommand MyCommand
    {
        get;
        private set;

    }

    // ... stuff ...
}

这里使用惰性初始化有什么好处?它必须在设置绑定(bind)时调用 get 属性,所以我看不出有什么理由在构造函数中使用此方法来设置东西。

我是不是漏掉了什么?

最佳答案

实际上,WPF 和 Silverlight 每次绑定(bind)只会获取一次中继命令,因此您实际上根本不需要存储支持字段:

public ICommand MyCommand
{
    get
    {
        return new RelayCommand(p => DoSomething());
    }
}

因此,虽然按照您的建议在 .ctor 中创建它没有任何问题,但没有什么理由这样做。

关于c# - 为什么 RelayCommands 通常使用惰性初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3769918/

相关文章:

android - 在 MVVM 架构中从 ViewModel 启动 Activity 的最佳方法

c# - WP8中连续调用两个接口(interface)方法

c# - 将 List<int> 作为查询参数传递给 SQL Server

c# - 对注册表进行碎片整理

c# - 用于撤消命令的 UWP TextBox 方法

c# - WPF 路径绑定(bind)到 PointCollection 不更新 UI

c# - ResourceDictionary WPF 样式中的交互触发器

c# - 有没有更简单的方法可以将多个可观察集合组合成一个可观察集合?

c# - 必须在 ListView 'ListView1' 上定义 ItemTemplate。有人帮我解决这个错误

C# - 减小图像大小的最佳方法是什么(用于通过 tcp 进行流式传输)