Bil*_*lie 5 .net c# events delegates event-handling
我需要创建一个Windows窗体应用程序,它能够发送数据并从另一个Form
实例接收数据.什么意思,Form
是发布者和订阅者,两者都是.
不幸的是,那天我病了,那天我不能参加讲座.
我再解释一下:
我有一个小聊天Form
,他有:新实例按钮,收到消息和发送消息.
你可以在下面看到:
当我发送消息时,它将显示在所有实例的"已接收"文本框中.
我想我需要使用委托和事件.
怎么办?谢谢!!
这是一个快速解决方案..如果您有任何疑问或者您发现评论令人困惑,请告诉我.
这是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);
}
}
Run Code Online (Sandbox Code Playgroud)
}
这是我创建的Messages类,用于处理在Forms之间发送的"中央"消息列表.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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
另外..为了正确"显示"消息,不要忘记将ListView控件的"View"属性设置为"List".一种更简单(也更首选的方式)就是使用ObservableCollection列表类型,它已经提供了一个可以订阅的事件.
希望这可以帮助.
归档时间: |
|
查看次数: |
9744 次 |
最近记录: |