I recently upgraded from MVVMLight 3 to 4, and noticed that my Commands broke. It turns out that the use of weak references in the new RelayCommand (implemented in version 3.5) were causing a code construct that I am using to fail. I know that there is some argument for weak refs relating to memory leak, I just don't understand it.
This fails:
private void InitCommand()
{
Command = new SwitchMainGridCommand<SwitchMainGridToolViewModel>(this).Command;
}
By fails, I mean that when I go to use the Command property that I had initialized and bound to, its backing methods have been garbage collected and the Command fails to execute. Interestingly, the Command object is still present, just the support properties on SwitchMainGridCommand are now gone. Before weak refs in RelayCommand, the ref to Command kept the support properties available as well, even though SwitchMainGridCommand was not being explicitly preserved.
This succeeds:
SwitchMainGridCommand<SwitchMainGridToolViewModel> _refHolder = null;
private void InitCommand()
{
_refHolder = new SwitchMainGridCommand<SwitchMainGridToolViewModel>(this);
Command = _refHolder.Command;
}
Creating a _refHolder class variable on the ViewModel where Command is being assigned would keep the methods / properties that _refHolder.Command referenced from being collected.
I guess this is the desired behavior of a weak reference, I am just not sure why it is desired.