Create a new ICommand object in the ViewModel
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 i开发者_如何转开发ts 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); }
}
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
private LightCommand _deleteDocumentCommand;
public LightCommand DeleteDocumentCommand
{
get
{
if (_deleteDocumentCommand == null)
{
_deleteDocumentCommand = new LightCommand(
() => DeleteDocument(), () => CanDeleteDocument);
}
return _deleteDocumentCommand;
}
}
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.
yes it would. You are better off instantiating it once, so that you have something like this:
LightCommand DeleteCommand { get; set;}
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.
精彩评论