我创建了一个userControl,名字是UserControl1。在这个用户控件上,我创建了一个按钮,名称是 btnAdd。我创建了 2 个表单,名称分别是 Form1 和 Form2。然后我在这些表单上添加 UserControl1。我想当我单击 Form1 上的 btnAdd 按钮时显示字符串“this is form 1”,如果我单击 Form2 上的 btnAdd 按钮然后显示字符串“this is form 2”。
我想使用委托(delegate)和事件来做到这一点。你可以帮帮我吗。 非常感谢。
我的代码跟随但没有运行。真正的结果必须显示在消息框“添加成功”:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
namespace EventDelegateUserControl
{
public partial class UC_them : UserControl
{
public UC_them()
{
InitializeComponent();
}
public delegate void ThemClickHandler(object sender, EventArgs e);
public event ThemClickHandler ThemClick;
public void OnThemClick(EventArgs e)
{
if (ThemClick != null)
{
ThemClick(this,e);
}
}
public void add()
{
OnThemClick(EventArgs.Empty);
}
public void btnThem_Click(object sender, EventArgs e)
{
add();
}
}
//---------------------------
public partial class Form1 : Form
{
public UC_them uc_them =new UC_them();
public Form1()
{
InitializeComponent();
}
public void dangky(UC_them uc_them)
{
uc_them.ThemClick += new UC_them.ThemClickHandler(uc_them_ThemClick);
}
void uc_them_ThemClick(object sender, EventArgs e)
{
MessageBox.Show("Add successful");
}
}
//----------------------------
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
UC_them them = new UC_them();
Form1 form1 = new Form1();
form1.dangky(them);
}
}
}
最佳答案
您的委托(delegate)/事件相关代码是正确的。 Main 方法的问题。
Application.Run(new Form1());
UC_them them = new UC_them();
Form1 form1 = new Form1();
form1.dangky(them);
您在 main 方法中创建了 Form1 的两个实例。 Application.Run(first instance) 方法中的一个实例,然后创建另一个实例。您仅为第二个实例设置事件绑定(bind)。但实际上只有第一个实例在运行。
如果您如下更改主要方法,它应该可以工作。
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
UC_them them = new UC_them();
Form1 form1 = new Form1();
form1.dangky(them);
Application.Run(form1);
}
关于c# - 如何在用户控件中使用委托(delegate)和事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6509847/