当您需要两个用户控件(winforms)进行通信时,最佳做法 [英] Best practice when you need two user controls (winforms) to communicate

查看:107
本文介绍了当您需要两个用户控件(winforms)进行通信时,最佳做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

扩展问题



除了以下指定的原始问题,我还要添加一个新问题。应用程序中的一个用户控件包含我需要从另一个用户控件访问的对象列表。如何才能做到这一点? (我不相信这个部门是很好的执行,但我宁愿不改变它。)



我应该像事件一样做原来的问题,还是应该保留父表单,并使用它来查找控件的实例,并将其公开为属性?






原始问题



我有两个用户控件,我想要能够相互通信。用户控制A应该能够在B上开始一个操作。



解决这个问题的首选方法是什么?表单等待A的事件,然后在B上开始操作?任何设计模式为此?还是更容易解决?



提前感谢! :)

解决方案

这两个用户控件应该彼此不了解。如果你想一直处理它们,请考虑创建一个第三个用户控件来放置它们。


如果表单等待来自A的事件,然后在B上开始操作?


是的,这是处理此问题的唯一好办法。 >

扩展(奖金?)问题有点棘手。我将通过将表单通过用户控件将代理传递给另一个用户控件上的方法来检索数据来处理此问题。然后,用户控件可以调用委托方法来调用另一个控件上的方法,而不了解其实现。


Extended problem

I would like to add a new problem in addition to the original problem specified below. One of the user controls in the application contains a list of objects that I need to access from another user control. How can this be done? (I don't believe the division into controls is very well performed, but I'd rather not change it..)

Should I do it by events as with the original problem, or should I get hold of the parent Form, and use it to find the instance of the control, and expose it as a property?


Original problem

I have two user controls in a form that I want to be able to communicate with each other. Usercontrol A should be able to start an operation on B.

What is the preferred way of solving this? Should the form wait for an Event from A, and then start the operation on B? Any design pattern for this? Or is it an even easier solution?

Thanks in advance! :)

解决方案

The two user controls should not have any knowledge of each other. If you want to always deal with them as a pair, consider creating a third user control to house them.

Should the form wait for an Event from A, and then start the operation on B?

Yes, this is the only good way to handle this.

The extended (bonus?) problem is a bit trickier. I would handle this by having the form pass the user control a delegate to a method on the other user control to retrieve the data. The user control can then invoke the delegate method to call the method on the other control without having any knowledge of its implementation.

这篇关于当您需要两个用户控件(winforms)进行通信时,最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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