My problem is hard to explain, so I created an example to show here.
When the WPF window is displayed in the example below, three buttons are displayed, each with a different text.
When I press any of these buttons, I assume that the text should be displayed in the message, but instead they all display the same message, as if they all used the event handler of the last button.
public partial class Window1 : Window { public Window1() { InitializeComponent(); var stackPanel = new StackPanel(); this.Content = stackPanel; var n = new KeyValuePair<string, Action>[] { new KeyValuePair<string, Action>("I", () => MessageBox.Show("I")), new KeyValuePair<string, Action>("II", () => MessageBox.Show("II")), new KeyValuePair<string, Action>("III", () => MessageBox.Show("III")) }; foreach (var a in n) { Button b = new Button(); b.Content = a.Key; b.Click += (x, y) => a.Value(); stackPanel.Children.Add(b); } } }
Does anyone know what is wrong?
source share