2

I would like to create some menu items in a loop from a list. I tried it that way:

MenuItem mnuItemDepth = new MenuItem();
foreach (ClassDepth depth in ClassDepths.ListOfDepths)
{
    MenuItem it = new MenuItem();
    it.Header = depth.name;
    it.Click += new RoutedEventHandler((s, a) => { ChangeDepth(depth); });
    mnuItemDepths.Items.Add(it);
}

Each item of ClassDepths.ListOfDepths should be made to a menu item. It works except one thing:

The click event triggers the ChangeDepth method with the same parameter (depth) for each menu item. It seems that the last menu item that is added defines the depth parameter that is passed to ChangeDepth by the event handler for each menu item that is created from the list. Does anyone know why? The menu items are different but ChangeDepth is called with the same parameter for each menu item.

I hope my explanation is not that bad. Thank you!

1 Answer 1

1

This is a matter of capturing the loop variable 'depth' in your closure. You can read a much better explanation than I can give here. To make this code work as you would expect simply copy the loop variable into a local variable and pass it instead:

MenuItem mnuItemDepth = new MenuItem();
foreach (ClassDepth depth in ClassDepths.ListOfDepths)
{
    var tempDepth = depth;  //capture the loop variable here
    MenuItem it = new MenuItem();
    it.Header = depth.name;
    it.Click += new RoutedEventHandler((s, a) => { ChangeDepth(tempDepth); });
    mnuItemDepths.Items.Add(it);
}
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.