如何在主窗体中使用用户控件复选框事件。

时间:2013-04-12 12:34:01

标签: c# winforms

我正在尝试使用C#windows窗体应用程序创建GUI。我在mainfrom中写了一个方法。我在其中一个用户控件中有两个复选框。当复选框发生变化时,我需要在主窗体中引发该事件并运行我在mainfrom中编写的方法。我怎么能这样做?。

4 个答案:

答案 0 :(得分:0)

在帮助中查找代表。您可以在主框中创建一个过程,控件中的委托,将委托设置为主过程中的过程,然后调用复选框。检查。

一项警告工作 - 检查代理是否为空(意味着它未设置),否则您将收到错误。

答案 1 :(得分:0)

public class MainForm : Form
{
    public void YourMethod()
    {
        ///
    }
}

public class UserControl
{
    private readonly MainForm _MainForm;

    public UserControl(MainForm mainForm)
    {
        _MainForm = mainForm;

        ///add event for checkbox
    }

    private void Checkbox_Clicked(object Sender, EventArgs e)
    {
        _MainForm.YourMethod();
    }

}

答案 2 :(得分:0)

在您的用户控件中执行以下操作(例如,根据我自己的自定义控件进行调整,将其调整为您显然需要的内容:)):

public event EventHandler InnerDiagramCheckBox1CheckChanged;

private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
    if (InnerDiagramCheckBox1CheckChanged != null)
    {
        InnerDiagramCheckBox1CheckChanged(sender, e);
    }
}

然后你可以在主要表单中对其加载或构造执行的操作是:

instanceofyourcontrol.InnerDiagramCheckBox1CheckChanged+= new 
System.EventHandler(nameofthefunctionyouwanttotriggerinthemainform);

您在此处执行的操作是将事件委派给您的用户控件:)

答案 3 :(得分:0)

在用户控件中创建委托,并使其以主窗体指向该函数。为usercontrol中的复选框创建OnCheckedChanged()事件,并在事件中调用委托方法。

查看此示例

mainform.cs

mainform_load()
{
// Initialize user control delegate object to point the method in mainform
usercontrol1.method= Method1;
...
}

// method to call from usercontrol
public void Method1()
{

}

usercontrol1.cs

delegate void Method1()
public PointMyMethod method;

...

checkbox1_OnCheckedChanged()
{
    // This calls the method in mainform
    method();
}

...

希望有所帮助