在用户控件之间传递数据 c# [英] Passing data between usercontrols c#

查看:36
本文介绍了在用户控件之间传递数据 c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

众所周知,有一些与此类似的解决方案,但我无法用它们解决我的问题.我有两个用户控件:

It's known that there are some solutions similar to this one, but I can't solve my problem with them. I have two user controls:

  • 第一个创建一个 Report 对象.
  • 第二个展示了它.

我有一个链接两个控件的主表单.

I have a main Form that links both controls.

这两个控件是在一个 DLL 中创建的,并添加到像这样的主要形式:

These two controls are created in a DLL, and are added to the main form like this:

//ADDS THE FIRST CONTROL TO THE PANEL CONTROL
  myDll.controlUserReport userControlA = new myDll.controlUserReport();
  panelControl1.Controls.Add(userControlA);
  userControlA.Dock = DockStyle.Left;

//ADDS THE SECOND CONTROL TO THE PANEL CONTROL
   myDll.controlDocViewer userControlB = new myDll.controlDocViewer();
   panelControl1.Controls.Add(userControlB);
   userControlB.Dock = DockStyle.Fill;

如何将在单击按钮时在第一个控件 controlUserReport 中创建的 Report 对象传递给另一个用户控件 controlDocViewer 以显示它?

How can I pass the Report object, which is created in the first control controlUserReport when I click over a button, to the other user control controlDocViewer to show it?

推荐答案

您应该为此使用事件.在 UserControlA 中声明事件:

You should use events for this. In UserControlA declare the event:

//Declare EventHandler outside of class
public delegate void MyEventHandler(object source, Report r);

public class UserControlA
{
    public event MyEventHandler OnShowReport;

    private void btnShowReport_Click(object sender, Report r)
    {
         OnShowReport?.Invoke(this, this.Report);
    }
}

UserControlB中订阅事件并显示报告:

In UserControlB subscribe to the event and show the report:

public class UserControlB
{
    // Do it in Form_Load or so ...
    private void init()
    {
       userControlA.OnShowReport += userControlA_OnShowReport;
    }

    private void userControlA_OnShowReport(object sender, Report r)
    {
        // Show the report
        this.ShowReport(r);
    }
}

这篇关于在用户控件之间传递数据 c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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