在 ViewModel 中创建一个新的 ICommand 对象
两个 ICommand 对象都绑定到 ViewModel。
第一种方法似乎经常使用。
但是第二个节省了一些代码行,但是当刷新 Binding 时它不会每次都创建一个新的 ICommand 对象,这样会浪费资源吗?!
private LightCommand _deleteDocumentCommand;
public LightCommand DeleteDocumentCommand
{
get { return _deleteDocumentCommand ?? (_deleteDocumentCommand = new LightCommand(() => DeleteDocument(), () => CanDeleteDocument)); }
}
public LightCommand DeleteDocumentCommand
{
get { return new LightCommand(() => DeleteDocument(), () => CanDeleteDocument); }
}
Both ICommand objects are bound to a ViewModel.
The first approach seems to be used often.
But the second one saves some lines of code but would it not create everytime a new ICommand object when the Binding is refreshed so its a waste of resources?!
private LightCommand _deleteDocumentCommand;
public LightCommand DeleteDocumentCommand
{
get { return _deleteDocumentCommand ?? (_deleteDocumentCommand = new LightCommand(() => DeleteDocument(), () => CanDeleteDocument)); }
}
public LightCommand DeleteDocumentCommand
{
get { return new LightCommand(() => DeleteDocument(), () => CanDeleteDocument); }
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,每次引用命令时,您的第二种方法都会创建一个新命令,但我也发现您的第一种方法很难阅读。
我在 ViewModel 中创建命令的首选方法是
它可能会包含更多行代码,但很容易阅读和理解。此外,通常我所有的公共属性/命令都是由宏生成的,并转储到
#region Properties
区域中,该区域在我使用 ViewModel 的整个过程中都保持折叠状态,因此我不必滚动页面获取/设置方法。Yes your 2nd method creates a new command every time the command is referenced, but I also find your 1st method rather hard to read.
My preferred way to make a command in the ViewModel is
It might be more lines of code, but it is easy to read and understand. Besides, usually all my public Properties/Commands are generated by macros and dumped into a
#region Properties
area that stays collapsed the entire time I work with the ViewModel, so I don't have to scroll through pages of get/set methods.是的,会的。您最好将其实例化一次,这样您就可以得到如下所示的内容:
然后在我们的 VM 实例化中分配给它。或者你可以使用你的第一个例子。
yes it would. You are better off instantiating it once, so that you have something like this:
and then in our VM instantiation you assign to it. Or you could use your first example.
我假设您正在寻找验证,这是正确的:
每次刷新绑定(或调用命令)时,都会实例化一个新对象。这看起来明显是资源浪费。
I assume you're looking for verification, and that's correct:
Everytime the Binding is refreshed, (or the command is called), a new object is instantiated. It looks like a clear waste of resources.