非现有按钮上的事件

时间:2013-09-06 12:56:41

标签: c# wpf

我正在使用WPF应用程序,我想动态添加按钮。 例如,我有一个循环,它添加了5个新按钮。

int i;

for (i = 0; i < 5; i++)
{
    Button addButton = new Button();
    addButton.Name = "addButton" + i;
    addButton.Content = "addButton" + i;
    this.devicesButtonStackPanel.Children.Add(addButton);
}

现在我在StackPanel中有5个按钮。

我需要在每个按钮上发生事件。

我正在尝试使用它:

private void addButton0_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    MessageBox.Show("test");
}

但它不起作用。

4 个答案:

答案 0 :(得分:5)

创建按钮时需要绑定到事件:

Button addButton = new Button();
addButton.Name = "addButton" + i;
addButton.Content = "addButton" + i;
// Bind your handler to the MouseDoubleClick event
addButton.MouseDoubleClick += addButton0_MouseDoubleClick;
this.devicesButtonStackPanel.Children.Add(addButton);

答案 1 :(得分:3)

您只需在代码中执行此操作

                Button addbutton = new Button();
                addbutton.Click += addButton0_MouseDoubleClick;

答案 2 :(得分:2)

只需订阅处理程序的每个按钮

addButton.Clicked += addButton0_MouseDoubleClick;

答案 3 :(得分:1)

您尚未将event handler附加到MouseDoubleClick event。请将您的控件事件附加到事件处理程序方法,如下所示:

addButton.MouseDoubleClick += addButton0_MouseDoubleClick;

您的代码应该与下面的代码段类似:

int i;

for (i = 0; i < 5; i++)
{
    Button addButton = new Button();
    addButton.Name = "addButton" + i;
    addButton.Content = "addButton" + i;
  //Use the addition assignment operator (+=) to attach your event handler to the event.
    addButton.MouseDoubleClick += addButton0_MouseDoubleClick;
    this.devicesButtonStackPanel.Children.Add(addButton);
}

您可以使用以下按钮进行操作:

  private void addButton0_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
       string buttonName = ((Button)sender).Name;
       string buttonNumber = buttonName.SubString(0,buttonName.Length -1 );

       switch(buttonNumber)
       {
         case "0":
         // do work for 0
          break;
          case "1":
          // do work for 1
         break;
        } 
    }

参见: How to: Subscribe to and Unsubscribe from Events (C# Programming Guide)