简体   繁体   English

如何在不同的Winform之间进行通信

[英]How to communicate between different winforms

I have a container WinForm called frmMain which holds another forms like frmOrder , frmMessage , the subforms was added in a TabPage control. 我有一个名为frmMain WinForm容器,其中包含另一个窗体,如frmOrderfrmMessage ,这些子窗体已添加到TabPage控件中。

What I want to do is communicating between subforms, say user changes something in frmOrder and frmMessage need to be notified, currently I think the communication need to be delegated through the frmMain . 我想做的是在子窗体之间进行通信,比如说用户在frmOrder更改,需要通知frmMessage ,目前我认为通信需要通过frmMain委派。

One solution I can think is to make subforms deriving from my custom Form derived class which defines interface say: 我可以想到的一种解决方案是,使子Form派生自我的自定义Form派生类,该类定义了接口,例如:

public class MessageEnabledForm: Form 
{
    public void SendMessage(String destFormName, String messageType, String data);
    public void ReceiveMessage(String destFormName, String messageType, String data);
}

I don't know whether this is feasible, and is there any other solutions I can employ? 我不知道这是否可行,还有其他解决方案可以使用吗? which is generic and needn't to know the concrete subform. 这是通用的,不需要知道具体的子表单。

Based on your question, I don't think inheritance is the best tool for the job. 根据您的问题,我认为继承不是工作的最佳工具。 I say its not the best choice because you are not dealing with an "is a" relationship. 我说这不是最佳选择,因为您没有处理“是”关系。 I think you should consider using Events and Delegates to handle the communication between forms and subforms. 我认为您应该考虑使用事件和委托来处理表单和子表单之间的通信。 The following MSDN article provides a good overview of Handling and Raising Events . 下面的MSDN文章很好地概述了处理和引发事件 You also may want to refresh yourself on the .NET INotifyPropertyChanged Interface if you using data binding in the subforms. 如果在子窗体中使用数据绑定,则可能还需要在.NET INotifyPropertyChanged接口上刷新自己。

You could use an Interface like this, that all the child forms implement: 您可以使用这样的接口 ,所有子窗体都可以实现:

public interface Communication
{
    public delegate void SendMessageDelegate(String destFormName, String messageType, String data);
    public event SendMessageDelegate SendMessage;

    public void ReceiveMessage(String destFormName, String messageType, String data);
}

When the main form receives the event, it can iterate over its "child" forms looking for a match on destFormName then call its ReceiveMessage() implementation (after casting it to the Communication interface). 当主窗体接收到该事件时,它可以遍历其“子”窗体以在destFormName上寻找匹配项,然后调用其ReceiveMessage()实现(将其强制转换为Communication接口之后)。

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

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