如何使自定义控件中的按钮触发onClick事件,并在自定义控件驻留的主窗体中处理它

本文关键字:自定义控件 处理 窗体 事件 按钮 何使 onClick | 更新日期: 2023-09-27 18:01:44

在c#中,我创建了一个继承自UserControl的自定义控件,并在自定义控件中添加了一个按钮btnInTrayMap。然后我将自定义控件添加到主表单中。主表单有另一个按钮用于比较它们的行为。我观察到的是主表单上的按钮在点击时工作正常。然而,位于自定义控件中的按钮btnInTrayMap在点击时根本没有响应。

对于自定义控件中的按钮,我有以下代码:

public partial class TrayMap : UserControl
{                      
    public TrayMap()
    {                                    
        InitializeComponent();               
    }        
    public event EventHandler MyCustomClickEvent;
    protected virtual void OnMyCustomClickEvent(object sender, EventArgs e)
    {            
        if (MyCustomClickEvent != null)
            MyCustomClickEvent(this, e);
    }
    private void btnInTrayMap_Click(object sender, EventArgs e)
    {            
        OnMyCustomClickEvent(sender, EventArgs.Empty);            
    } 
}

我相信btnTrayMap。TrayMap.designer.cs中的Click事件处理程序可能导致了这个问题:

this.btnInTrayMap.Click += new System.EventHandler(this.btnInTrayMap_Click);
在主表单中,我有下面的代码:
public partial class Form1 : Form
{        
    public Form1()
    {
        InitializeComponent();
    }
    private void btnInForm_Click(object sender, EventArgs e)
    {
        MessageBox.Show("Test Button In Form", "btnInForm Button Clicked", MessageBoxButtons.OK);
    }
    public void MyCustomClickEvent(object sender, EventArgs e)
    {
        Button button = sender as Button;
        MessageBox.Show("Test Button In TrayMap", button.Text + " Button Clicked", MessageBoxButtons.OK);
    }
}

我想知道如何设置事件委托,以便在主表单中的MyCustomClickEvent方法将在按钮btnInTrayMap被单击时执行。谢谢你。

如何使自定义控件中的按钮触发onClick事件,并在自定义控件驻留的主窗体中处理它

您没有在主窗体中注册您的事件。试试这个方法。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        trayMap.MyCustomClickEvent += MyCustomClickEvent;  // i'm assuming trayMap is the name of user control in main form.
    }
    private void btnInForm_Click(object sender, EventArgs e)
    {
        MessageBox.Show("Test Button In Form", "btnInForm Button Clicked", MessageBoxButtons.OK);
    }
    private void MyCustomClickEvent(object sender, EventArgs e)
    {
        Button button = sender as Button;
        MessageBox.Show("Test Button In TrayMap", button.Text + " Button Clicked", MessageBoxButtons.OK);
    }
}