简体   繁体   English

不同形式之间的沟通

[英]Communication between different forms

In C#, using winforms, what is the best way to make forms talk to each other? 在C#中,使用winforms,使表单相互交流的最佳方法是什么? Sending data, messages, strings, whatever, from on to the other? 将数据,消息,字符串等等发送到另一个?

Delegates? 代表们?

Ideas? 想法?

We'ved used something called the Event Pattern successfully in several Winform applications. 我们在几个Winform应用程序中成功使用了一个名为Event Pattern的东西。 Here's a good link that will help you get started. 这是一个很好的链接 ,可以帮助您入门。

You can create events in one form and then register for those events in the other form. 您可以在一个表单中创建事件,然后以其他形式注册这些事件。 You can also simply access properties from one form to the other. 您还可以简单地访问从一个表单到另一个表单的属性。 For example maybe in the constructor of the second form, you would pass a variable for the first form. 例如,可能在第二种形式的构造函数中,您将为第一种形式传递变量。

It sounds like what you're looking for are events though. 听起来你正在寻找的是事件。 When some event happens any delegate that is registered will be called. 当某些事件发生时,将调用任何已注册的代理。

There is a tutorial on MSDN for events here . MSDN上有一个关于事件教程

all depends on what you want to communicate. 一切都取决于你想要沟通的内容。

Let's say it is configuration data; 假设它是配置数据; You could create a static property on main form called Settings, which would expose your object. 您可以在名为Settings的主窗体上创建一个静态属性,这将暴露您的对象。 Than all forms would see that same Settings instance, and all would see any changes. 比所有表单都看到相同的Settings实例,并且所有表单都会看到任何更改。

for extra credit you could implement INotifyPropertyChanged, and have it trigger an event. 要获得额外的功劳,您可以实施INotifyPropertyChanged,并让它触发一个事件。 that way all forms looking at Settings would be notified if anything changed. 这样,如果有任何变化,将通知所有查看设置的表单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM