C# -> C#订阅事件

可以在用户控件中添加一个事件,并在主窗体中订阅该事件。

具体做法如下:

  1. 在用户控件中添加一个 PictureBox 控件,并为其添加一个 Click 事件。

  2. 在该事件中触发一个自定义事件,并传递需要的参数。

  3. 在主窗体中定义一个方法,用于处理自定义事件。

  4. 在主窗体的构造函数中订阅自定义事件。

以下是具体代码实现:

在用户控件中添加 PictureBox 控件和 Click 事件

复制代码
public partial class ModbusWareHouseOneControl : UserControl
{
    // 定义自定义事件
    public event EventHandler<PictureBoxClickEventArgs> PictureBoxClick;

    public ModbusWareHouseOneControl()
    {
        InitializeComponent();
    }

    private void pictureBox1_Click(object sender, EventArgs e)
    {
        // 触发自定义事件,并传递需要的参数
        PictureBoxClick?.Invoke(this, new PictureBoxClickEventArgs("参数1", "参数2"));
    }
}

在主窗体中定义方法,用于处理自定义事件

复制代码
public partial class MainForm2 : Form
{
    public MainForm2()
    {
        InitializeComponent();

        // 订阅自定义事件
        modbusWareHouseOneControl1.PictureBoxClick += ModbusWareHouseOneControl_PictureBoxClick;
    }

    private void ModbusWareHouseOneControl_PictureBoxClick(object sender, PictureBoxClickEventArgs e)
    {
        // 处理自定义事件
        // ...
    }
}

自定义事件的参数类型为 PictureBoxClickEventArgs,可以根据需要自行定义。在上面的示例中,参数类型包含两个字符串类型的属性,分别为 Param1Param2

复制代码
public class PictureBoxClickEventArgs : EventArgs
{
    public string Param1 { get; private set; }
    public string Param2 { get; private set; }

    public PictureBoxClickEventArgs(string param1, string param2)
    {
        this.Param1 = param1;
        this.Param2 = param2;
    }
}

这样,在用户控件中,当 PictureBox 被点击时,会触发自定义事件,并将参数传递给主窗体中的处理方法进行处理。

案例一:

筒仓三维超声波扫描料位计(删除用户控件用法)

相关推荐
小码编匠13 小时前
WPF 中的高级交互通过右键拖动实现图像灵活缩放
后端·c#·.net
唐青枫20 小时前
C#.NET 定时任务与队列利器:Hangfire 完整教程
c#·.net
hez20101 天前
Runtime Async - 步入高性能异步时代
c#·.net·.net core·clr
mudtools2 天前
.NET驾驭Word之力:玩转文本与格式
c#·.net
唐青枫2 天前
C#.NET 数据库开发提速秘籍:SqlSugar 实战详解
c#·.net
mudtools2 天前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
大飞pkz3 天前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
唐青枫3 天前
从入门到进阶:C#.NET Stopwatch 计时与性能测量全攻略
c#·.net
未来之窗软件服务3 天前
幽冥大陆(二)RDIFSDK 接口文档:布草洗涤厂高效运营的技术桥梁C#—东方仙盟
开发语言·c#·rdif·仙盟创梦ide·东方仙盟
1uther3 天前
Unity核心概念⑨:Screen
开发语言·游戏·unity·c#·游戏引擎