4

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;

            });
  • I just ran into this same bug. Definitely should be reported if it hasn't already. – devuxer Mar 01 '16 at 01:48
  • 1
    Didn't see a bug report, so I added one: https://mvvmlight.codeplex.com/workitem/7721. If you'd like to see this fixed, please upvote the bug. Thanks. – devuxer Mar 01 '16 at 02:24

1 Answers1

2

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.

josh2112
  • 829
  • 6
  • 22