2012-12-05 12 views
5

Verileri gönderebilen ve başka bir Form örneğinden veri alabilen bir Windows Form uygulaması oluşturmam gerekiyor. Ne demek, Form, her ikisi de bir yayıncı ve bir abone.Formlar arasında veri göndermek için olaylar nasıl kullanılır?

Ne yazık ki, o gün hastaydım ve o gün ders olamazdı.

Ben küçük bir sohbet Form, var:

Tekrar açıklayacağım, yeni Örnek düğmesine alınan mesajlar ve mesaj göndermek.

hemen altında görebileceğiniz gibi:

enter image description here

Ben bir mesaj göndermek zaman, tüm örnekleri arasında "Recieved" metin gösterilecektir.

ben delege ve olayları kullanmak gerekir tahmin.

Nasıl bunu? Teşekkürler!!

+0

"gözlemci" desen bir göz atın. http://msdn.microsoft.com/en-us/library/ee817669.aspx –

cevap

7

Burada hızlı çözüm .. Herhangi bir sorunuz olursa bize bildirin ya da kafa karıştırıcı bir yorum ..

bulursanız Burada Form sınıfı (kod arkasında) bulunuyor. Form bir kez oluşturulduğunda, bir ileti işleyicisinin Message sınıfı içindeki HandleMessage olayına "bağlanarak" bir olaya "abone olduğunu" unutmayın. Form sınıfında, ListView öğesinin koleksiyonunun bulunduğu yer burasıdır.

Yeni Form butonuna tıklandığında zaman, aynı form olsun en

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); 
    } 
} 
(aynı mantık Formunun tüm örneklerini tam olarak aynı olacağından bu kod yeniden kullanımına izin verir) oluşturuldu ve görüntülenen

}

İşte Formlar arasında gönderilen mesajların bir "merkez" listesi işlemek için oluşturulan bir Mesajları sınıfı. İletiler sınıfı, bir formun bir formunun tüm örneklerinde kalıcı olmasına izin veren bir tekildir (yani, yalnızca bir kez başlatılabilir). Tüm Formlar aynı listeyi paylaşır ve bir liste güncellendiğinde bildirim alır. Görebildiğiniz gibi, "HandleMessage" olayı, her bir formun oluşturulduğunda/gösterildiğinde abone olacağı Etkinlik'dir. Eğer NotifyNewMessage fonksiyonuna bir göz atacak olursak

, bu bir değişim olduğu abone olmuş bildirmek için mesajlar sınıfı tarafından çağrılır. EventArgs, abonelere veri aktarmak için kullanıldığından, yeni eklenen mesajları tüm abonelere iletmek için özel bir EventArgs oluşturdum.

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; 
     } 
    } 
} 

Ayrıca .. olmaya mesajları için sırayla doğru, "Listesi" üzere ListView denetimi set "Görünüm" özelliğini unutma "gösterilen". Daha kolay (ve tercih edilen bir yol), sadece abone olabileceğiniz bir etkinlik sağlayan ObservableCollection liste türünü kullanacaktır. Bu yardımcı olur

Umut.

+0

Tamam, teşekkürler, ben evde olacağım zaman deneyeceğim (çünkü dizüstü bilgisayarımda ubuntu kullanıyorum). Lütfen bana kısaca tarif eder misiniz orada yazdınız?Daha fazla bilgi sağlamak için – Billie

+0

@ user1798362 güncellendi. Başka sorularınız olursa lütfen bize bildirin .. –

+0

Delege ve Olayları kullanmıyor, ancak fikir açık. Teşekkürler. – Billie

İlgili konular