3

I want to dynamically add Commands to buttons. Each button should execute a function using the iterator variable as a parameter. The problem is, while the button text displays correctly, "0, 1, 2" on the buttons, the commands are all executed with the final value of the iterator, "SomeCommand(2)". How do I get the buttons to execute SomeCommand(0), SomeCommand(1) and SomeCommand(2) respectively?

public void DynamicButtons()
{
  for(int i = 0; i < 3; i++)
  {
    Button newButton = new Button { Command = new Command(() => { SomeFunction(i); }), Text = i.ToString() };
  }
}

1 Answer 1

3

You need to create a copy of your loop index and pass that.

When you create a lambda it stores a reference to the thing in the outer scope, not the value itself. So as your loop increments, everything has a reference to the counter, and so everything ends up with the value '2' when it comes to execute the command.

public void DynamicButtons()
{
  for(int i = 0; i < 3; i++)
  {
    var copy = i;

    Button newButton = new Button 
    { 
        Command = new Command(() => 
        { 
            SomeFunction(copy); 
        }), 
        Text = i.ToString() 
    };
  }
}

Further reading: https://blogs.msdn.microsoft.com/ericlippert/tag/closures/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.