Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GalaSoft MvvmLight RelayCommand stops working when accessing closure

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;

            });
like image 359
Jan Schweda Avatar asked Oct 27 '25 03:10

Jan Schweda


1 Answers

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.

like image 99
josh2112 Avatar answered Oct 30 '25 12:10

josh2112