Wil*_*lka 13 c# data-binding xaml mvvm 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 ...
}
Run Code Online (Sandbox Code Playgroud)
而不是在构造函数中创建RelayCommand,如下所示:
public class ViewModel
{
public ViewModel()
{
MyCommand = new RelayCommand(p => DoSomething());
}
public ICommand MyCommand
{
get;
private set;
}
// ... stuff ...
}
Run Code Online (Sandbox Code Playgroud)
在这里使用延迟初始化有什么好处?在设置绑定时必须调用get属性,所以我看不出在构造函数中使用此方法而不是设置的原因.
我在这里错过了什么吗?
Jud*_*ngo 15
实际上,WPF和Silverlight每次绑定只会获得一次relay命令,因此您根本不需要存储支持字段:
public ICommand MyCommand
{
get
{
return new RelayCommand(p => DoSomething());
}
}
Run Code Online (Sandbox Code Playgroud)
因此,虽然按照你的建议在.ctor中创建它没有任何问题,但是没有什么理由可以.
| 归档时间: |
|
| 查看次数: |
1566 次 |
| 最近记录: |