WPF按钮单击C#代码

我有一个按钮数组,它在运行时动态生成。 我在我的代码中有按钮单击function,但我找不到在代码中设置按钮的单击名称的方法。 所以,

什么是XAML的等效代码:

或者,我应该为“????”放置什么 在以下代码中:

Button btn = new Button()
btn.Name = "btn1";
btn.???? = "btn1_Click";

 Button btn = new Button(); btn.Name = "btn1"; btn.Click += btn1_Click; private void btn1_Click(object sender, RoutedEventArgs e) { // do something } 

以下应该做的伎俩:

 btn.Click += btn1_Click; 
 // sample C# public void populateButtons() { int xPos; int yPos; Random ranNum = new Random(); for (int i = 0; i < 50; i++) { Button foo = new Button(); Style buttonStyle = Window.Resources["CurvedButton"] as Style; int sizeValue = ranNum.Next(50); foo.Width = sizeValue; foo.Height = sizeValue; foo.Name = "button" + i; xPos = ranNum.Next(300); yPos = ranNum.Next(200); foo.HorizontalAlignment = HorizontalAlignment.Left; foo.VerticalAlignment = VerticalAlignment.Top; foo.Margin = new Thickness(xPos, yPos, 0, 0); foo.Style = buttonStyle; foo.Click += new RoutedEventHandler(buttonClick); LayoutRoot.Children.Add(foo); } } private void buttonClick(object sender, EventArgs e) { //do something or... Button clicked = (Button) sender; MessageBox.Show("Button's name is: " + clicked.Name); } 

我不认为WPF支持你想要实现的目标,即使用方法名称或btn1.Click =“btn1_Click”将方法分配给按钮。 您将不得不使用上述答案中建议的方法,即使用适当的方法注册按钮点击事件btn1。点击+ = btn1_Click;

你应该放在下面

 btn.Click = btn.Click + btn1_Click;