栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在用户控件中创建事件并在主窗体中处理它?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在用户控件中创建事件并在主窗体中处理它?

您需要为用户控件创建事件处理程序,该事件处理程序在触发用户控件中的事件时引发。这将使您能够在事件链上冒泡,以便可以从表单中处理事件。

当点击

Button1
UserControl时,我将
Button1_Click
触发
UserControl_ButtonClick
在表单上触发的事件:

用户控件:

[Browsable(true)] [Category("Action")] [Description("Invoked when user clicks button")]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 }

笔记:

  • 较新的Visual Studio版本建议

    if (this.ButtonClick!= null) this.ButtonClick(this, e);
    您代替使用
    ButtonClick?.Invoke(this, e);
    ,它的作用基本相同,但更短。

  • Browsable
    属性使事件在Visual Studio的设计器(事件视图)中可见,
    Category
    并在“动作”类别中显示该事件,并
    Description
    提供对其的描述。您可以完全省略这些属性,但是由于VS可以为您处理,因此使设计者可以轻松使用它们。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/421477.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号