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!