- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我需要创建一个能够发送数据和从另一个 Form
实例接收数据的 Windows 窗体应用程序。什么意思,Form
既是发布者又是订阅者。
不幸的是,那天我生病了,那天我不能去听课。
我再解释一下:
我有一个小聊天Form
,谁有:新的实例按钮、接收消息和发送消息。
如下图所示:
当我发送消息时,它会显示在 ALL INSTANCES 的“已接收”文本框中。
我想我需要使用委托(delegate)和事件。
怎么做?谢谢!!
最佳答案
这是一个快速解决方案。如果您有任何问题或发现评论令人困惑,请告诉我。
这是 Form 类(代码隐藏)。请注意,一旦实例化了表单,它就会通过将事件处理程序“连接”到 Message 类中的 HandleMessage 事件来“订阅”事件。在 Form 类中,这是填充 ListView 的项目集合的地方。
每当单击“新建表单”按钮时,都会创建并显示相同的表单(这允许代码重用,因为相同的逻辑对于表单的所有实例都是完全相同的)
public partial class Form1 : Form
{
Messages _messages = Messages.Instance; // Singleton reference to the Messages class. This contains the shared event
// and messages list.
/// <summary>
/// Initializes a new instance of the <see cref="Form1"/> class.
/// </summary>
public Form1()
{
InitializeComponent();
// Subscribe to the message event. This will allow the form to be notified whenever there's a new message.
//
_messages.HandleMessage += new EventHandler(OnHandleMessage);
// If there any existing messages that other forms have sent, populate list with them.
//
foreach (var messages in _messages.CurrentMessages)
{
listView1.Items.Add(messages);
}
}
/// <summary>
/// Handles the Click event of the buttonNewForm control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void buttonNewForm_Click(object sender, EventArgs e)
{
// Create a new form to display..
//
var newForm = new Form1();
newForm.Show();
}
/// <summary>
/// Handles the Click event of the buttonSend control. Adds a new message to the "central" message list.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void buttonSend_Click(object sender, EventArgs e)
{
string message = String.Format("{0} -- {1}", DateTime.UtcNow.ToLongTimeString(), textBox1.Text);
textBox1.Clear();
_messages.AddMessage(message);
}
/// <summary>
/// Called when [handle message].
/// This is called whenever a new message has been added to the "central" list.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="args">The <see cref="System.EventArgs"/> instance containing the event data.</param>
public void OnHandleMessage(object sender, EventArgs args)
{
var messageEvent = args as MessageEventArgs;
if (messageEvent != null)
{
string message = messageEvent.Message;
listView1.Items.Add(message);
}
}
这是我创建的一个 Messages 类,用于处理在 Form 之间发送的“中央”消息列表。 Messages 类是单例(意味着它只能实例化一次),它允许一个列表在 Form 的所有实例中持久存在。所有表单将共享同一个列表,并在列表更新时收到通知。如您所见,“HandleMessage”事件是每个表单在创建/显示时都会订阅的事件。
如果您看一下 NotifyNewMessage 函数,它会被 Messages 类调用以通知订阅者发生了变化。由于 EventArgs 用于将数据传递给订阅者,因此我创建了一个特殊的 EventArgs 来将新添加的消息传递给所有订阅者。
class Messages
{
private List<string> _messages = new List<string>();
private static readonly Messages _instance = new Messages();
public event EventHandler HandleMessage;
/// <summary>
/// Prevents a default instance of the <see cref="Messages"/> class from being created.
/// </summary>
private Messages()
{
}
/// <summary>
/// Gets the instance of the class.
/// </summary>
public static Messages Instance
{
get
{
return _instance;
}
}
/// <summary>
/// Gets the current messages list.
/// </summary>
public List<string> CurrentMessages
{
get
{
return _messages;
}
}
/// <summary>
/// Notifies any of the subscribers that a new message has been received.
/// </summary>
/// <param name="message">The message.</param>
public void NotifyNewMessage(string message)
{
EventHandler handler = HandleMessage;
if (handler != null)
{
// This will call the any form that is currently "wired" to the event, notifying them
// of the new message.
handler(this, new MessageEventArgs(message));
}
}
/// <summary>
/// Adds a new messages to the "central" list
/// </summary>
/// <param name="message">The message.</param>
public void AddMessage(string message)
{
_messages.Add(message);
NotifyNewMessage(message);
}
}
/// <summary>
/// Special Event Args used to pass the message data to the subscribers.
/// </summary>
class MessageEventArgs : EventArgs
{
private string _message = string.Empty;
public MessageEventArgs(string message)
{
_message = message;
}
public String Message
{
get
{
return _message;
}
}
}
另外..为了正确“显示”消息,不要忘记将 ListView 控件的“View”属性设置为“List”。一种更简单(也是首选)的方法是简单地使用 ObservableCollection 列表类型,它已经提供了一个您可以订阅的事件。
希望这对您有所帮助。
关于c# - 如何使用事件和委托(delegate)在表单之间发送数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13718728/
我看了很多文章,但我仍然不清楚我们通常创建的普通委托(delegate)和多播委托(delegate)之间的区别。 public delegate void MyMethodHandler(objec
考虑以下几点: Action a1 = new Action(_insert); Action a2 = new Action(a1); a2 指的是什么?它是 a1,a1 的浅拷贝还是 a1 的深拷
我希望这听起来像是一个显而易见的问题,但是委托(delegate)返回类型是否也必须与其委托(delegate)的方法的返回类型相匹配? EG,像这样: public static void Save
我想使用 Kotlin 委托(delegate),但我不想在委托(delegate)人之外创建委托(delegate)。委托(delegate)的所有示例都如下所示: interface Worker
class SuperClass { var delegate : SuperClassDelegate? } protocol SuperClassDelegate { func d
我有一个加载 View 的 View ,需要将 View 推送到主导航 Controller 。 我已经为每个 View 设置了一个委托(delegate),并且基本上使我的调用沿着“链”返回到主导航
为简单起见,假设我想创建一个自定义 UITextField 并向其添加一个简单的行为;也就是说,如果文本字段成为第一响应者,背景颜色将变为绿色。 为此,在我的自定义类中,我必须将该类设置为委托(del
我非常有信心我应该能够使用非静态方法的委托(delegate),但下面给了我一个错误: public class TestClass { private delegate void TestD
在 C# 中不能从 System.Delegate 或 System.MulticastDelegate 继承。只要您声明标准的“运行时托管”方法,就完全可以在 MSIL 中执行此操作。但是,每次我向
我在 Storyboard 中定义了一个 iPad 界面,带有一个 SplitViewController。我想将 SplitViewController 的委托(delegate)设置为指向详细 C
我有几个解析器。有一个顶级的可以委托(delegate)给另一个。 Parser我们从 Reader 中获取他们的输入(可变)。我只想要一个 Parser为了能够一次解析,只有一个解析器应该有 Rea
一直以来我都在阅读关于反射的文章,每个人都在说:“反射很慢”,“反射很慢”。 现在我决定测试速度有多慢,令我惊讶的是,使用反射创建的委托(delegate)实际上是使用 lambda 创建的委托(de
在 Xcode 4.5 中启动了 Cocos2D 2.1 模板(没有物理引擎),针对 iOS 6 和 iPad。在 CDAudioManager.m 文件中,以下代码... AVAudioSessio
以下是来自未管理的 dll 的函数代码。它接受一个函数指针作为参数,并简单地返回被调用函数返回的值。 extern __declspec(dllexport) int _stdcall callDe
//NewCharts.h #import @interface NewCharts : UIViewController @property(nonatomic,retain)IBOutlet U
鉴于以下 MSDN 示例代码,为什么我不能定义 Action 委托(delegate)“内联”: public static void Main(string[] args) { Action
在虚幻引擎中,UFUNCTION用于通过附加说明符来丰富功能,以用于蓝图使用、复制和委托(delegate)。 然而,一些委托(delegate)类型似乎不允许绑定(bind) UFUNCTION(如
我刚刚将照片选择器放入我的项目中,一切正常。唯一的事情是它坚持在我设置委托(delegate)的地方给我以下警告 - Assigning to 'id' from incompatible type
我有一个 UIImageView 的子类,并且想将 self 作为参数传递给委托(delegate)。我在 MyImageView 之前收到错误“预期 ')'”。我需要将对象传递给委托(delegat
我正在开发 iOS 10 的语音转文本功能。 我希望调用 SFSpeechRecognitionTaskDelegate 的委托(delegate)方法来检查完成的结果。 func speechRec
我是一名优秀的程序员,十分优秀!