I struggle using the GalaSoft.MvvmLight.RelayCommand. All is working fine until i try to Access a closure. I don't get any error or log output.
This Code is working:
 for (int i = 0; i < 3; i++)
            {
                var iTemp = i;
                var command = new RelayCommand(() =>
                {
                    Debug.WriteLine("executed");
                    Debug.WriteLine(this);
                    // Debug.WriteLine(iTemp);
                });
                Commands[i.ToString()] = command;
                children.Add(dataTemplateCreator.BuildButtonWithCommand(0, gridRow, $"Commands[{i}]", i.ToString()));
                gridRow++;
            }
As soon as i remove the Comment the Command is no longer executed. Has anyone seen this behavior before?
I also tried an easier
Works:
Execute = new RelayCommand(() =>
        {
            Value += 3;
        });
Stops working:
 var incValue = 3;
            Execute = new RelayCommand(() =>
            {
                Value += incValue;
            });
You've undoubtedly solved this or moved on, but your problem is garbage collection.
The problem is described in this Stack Overflow answer and the solution is described in this MVVMLight documentation item.
In short: The command action and enable function you pass to RelayCommand are stored with weak references, so unless something besides the RelayCommand is holding onto them, they will be garbage-collected at some point. The solution is to use the keepTargetAlive constructor parameter if your action or enable function are closures.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With