且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在窗口应用程序中的两个用户控件之间进行通信

更新时间:2023-10-19 17:29:58

好吧,假设您在UserControl2中放置了一个公开了GridView的公共属性:

//在UserControl2中
公开GridView uc2GridView {放; }

//在UserControl2的Load事件中:
uc2GridView = theGridView; //命名为GridView的任何内容

现在,创建了两个UserControl的窗体可以看到"公开的GridView ...,但是UserControl1无法.还是...想一想...因为UserControl1的父级可能是Form ...也许可以吗?

在这一点上,典型的解决方案是在UserControl1中让Button Click事件引发一个自定义事件,该事件将由该表单订阅:该自定义事件将正确地执行读取UserControl1中的TextBox数据,并将其传递给Form(可能使用自定义EventArgs类).然后,窗体可以使用对UserControl2中公开的GridView的访问来做正确的事情来对其进行操作,或者调用在UserControl1中可访问的Public方法来执行所需的操作.

现在,您可以采取的另一种策略是让UserControl1将其TextBoxes公开给Form,就像UserControl2公开其GridView一样.

但是,这仍然给您带来一个问题,即如何通知表单UserControl1中的按钮已被按下?

这就是您需要进行的工作:

1.如何创建EventArgs类来保存发生事件时需要传递的数据.

2.如何定义代表

3.如何在类或用户控件或外部代码可以预订的任何类中实现公共事件.

掌握这些基本技能,您将掌握C#,这真是棒极了!
Okay, let''s assume that you put a public property in UserControl2 that exposes the GridView:

// in UserControl2
public GridView uc2GridView { get; set; }

// in UserControl2''s Load event:
uc2GridView = theGridView; // whatever you named your GridView

Now your Form, which has created both UserControls, can ''see'' the exposed GridView ... but UserControl1 cannot. Or ... think a minute ... since the Parent of UserControl1 is probably the Form ... maybe it can ?

At this point a typical solution would be to have the Button Click event in UserControl1 raise a custom Event which would be subscribed to by the Form : that custom event would do the right thing to read the TextBox(es) data in UserControl1, and pass it to the Form (probably using a custom EventArgs class). And then the Form, using its access to the exposed GridView in UserControl2, can do the right thing to manipulate it, or call a Public method you''ve made accessible in UserControl1 to do what you need to do.

Now, another strategy you could pursue would be to have UserControl1 expose its TextBoxes to the Form, just like UserControl2 exposed its GridView.

But, that still leaves you with the issue of how do you notify the Form that the Button in UserControl1 has been pressed ?

And that''s what you need to work on:

1. How to create an EventArgs class to hold the data you need to pass when an Event occurs.

2. How to define a Delegate

3. How to implement a public Event in a class or usercontrol, or whatever, that external code can subscribe to.

Master these basic skills, and you will be on your way to mastery of C#, and what a great feeling that will be !