c# - 在运行时更改按钮名称和事件处理

标签 c# .net vb.net winforms

在我的 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/

相关文章:

c# - 如何从路径字符串中获取最后一个文件夹?

c# - 关键字 'this' (Me) 在调用基本构造函数时不可用

asp.net - 扩展/重写 System.Net.Mail.SmtpClient Send(message As MailMessage) 方法

c# - 如何通过 CodeBuild 从 AWS S3 下载文件

c# - CSharpCodeProvider 在编译期间使用自定义参数

.net - 确定应用程序是否在azure中运行

c# - UWP 应用程序发布编译中的 System.TimeZoneNotFoundException

c# - MVC DAL 和 BLL 概念

c# - 如何用具有相同文本的旧值替换字符串两次?

c# - 使用远程计算机上的 dll