如何在用户控件中进行事件并在主窗体中进行处理? [英] How do I make an Event in the Usercontrol and Have it Handeled in the Main Form?

查看:116
本文介绍了如何在用户控件中进行事件并在主窗体中进行处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义用户控件,我想做一些比较简单的事情。

I have a custom usercontrol and I want to do something relatively simple.

当用户控件的值变化时,数值上升,主窗体更新为显示窗口。

When ever a numeric up down in that usercontrol's value changes, have the main form update a display window.

这不是问题,如果NUD不在用户控件,但我似乎无法弄清楚如何让主窗体处理的事件不是用户控件。

This is not a problem if the NUD was not in a usercontrol but I can't seem to figure out how to have the event handled by the mainform and not the usercontrol.

推荐答案

您需要为用户控件中创建一个事件处理程序控制被解雇。这将允许您将链接上的事件提升到链中,以便您可以从表单处理事件。

You need to create an event handler for the user control that is raised when an event from within the user control is fired. This will allow you to bubble the event up the chain so you can handle the event from the form.

在UserControl上单击 Button1 时,我将触发 Button1_Click 它触发 UserControl_ButtonClick 在表单上:

When clicking Button1 on the UserControl, i'll fire Button1_Click which triggers UserControl_ButtonClick on the form:

用户控制:

public event EventHandler ButtonClick;

protected void Button1_Click(object sender, EventArgs e)
{
    //bubble the event up to the parent
    if (this.ButtonClick!= null)
        this.ButtonClick(this, e);               
}

表单:

UserControl1.ButtonClick += new EventHandler(UserControl_ButtonClick);

protected void UserControl_ButtonClick(object sender, EventArgs e)
{
    //handle the event 
}

这篇关于如何在用户控件中进行事件并在主窗体中进行处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆