在我的 winform 中,在我的表单的 designer.cs 部分
this.Button1.Text = "&Click";
this.Button1.Click += new System.EventHandler(this.Button1_Click);
在 form.cs 中
private void Button1_Click(object sender, System.EventArgs e)
{
//Code goes here.
}
在表单的一部分中,我有一个 TreeView ,当 TreeView 内容展开时,我需要重命名上面的按钮并连接一个不同的事件
Button1.Name = "ButtonTest";
ButtonTest.Click += new System.EventHandler(this.ButtonTest_Click);
但是这失败了,说没有找到 ButtonTest,我如何动态更改按钮的名称并调用不同的点击事件方法?
private void ButtonTest_Click(object sender, System.EventArgs e)
{
//Code goes here.
}
一旦它被称为 ButtonTest_Click,我需要将它重命名回 Button1,有什么想法吗?
最佳答案
Button1
引用一个变量名。该变量指向具有 Name
属性的 Button
类型的实例。如果您更改 Name
属性的值,它不会更改变量的名称。您仍然需要将该按钮称为 button1
。事实上,它并没有真正改变按钮的 Name
属性的值。 Name
属性的存在只是为了帮助 Windows 窗体设计者。
如果您想将事件处理程序从一种方法更改为另一种方法,您必须先取消订阅原始处理程序,然后再订阅新的处理程序。只需将您的代码更改为:
Button1.Name = "ButtonTest";
Button1.Click -= this.Button1_Click;
Button1.Click += this.ButtonTest_Click;
关于c# - 在运行时更改按钮名称和事件处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11855779/