不存在按钮上的事件
本文关键字:事件 按钮 不存在 | 更新日期: 2023-09-27 18:30:29
我正在开发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);
}
现在我在堆栈面板中有 5 个按钮。
我需要每个按钮上的事件。
我正在尝试使用这个:
private void addButton0_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
MessageBox.Show("test");
}
但它不起作用。
创建按钮时需要绑定到事件:
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);
您只需在代码中执行此操作即可
Button addbutton = new Button();
addbutton.Click += addButton0_MouseDoubleClick;
只需订阅每个按钮的处理程序
addButton.Clicked += addButton0_MouseDoubleClick;
您尚未将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;
}
}
指:如何:订阅和取消订阅事件(C# 编程指南)