Hi everyone,
I'm trying handle events from a list of business object.
Actually, i'm wondering if it's possible to write something like that: ObjectsList<>.Changed += new ChangedEventHandler(ListChanged);
to generic subscribe at all "Changed" event produce by the items attached to the list "ObjectsList".
belows the csharp code where i have tried to implement the concept.
Thx in advance for your help,
Best regards,
Cedric
using System;
using System.Collections.Generic;
using System.Text;
namespace CollectionApplication
{
// A delegate type for hooking up change notifications.
public delegate void ChangedEventHandler(object sender, EventArgs e);
class MyObject
{
// An event that clients can use to be notified whenever the elements is changed.
public event ChangedEventHandler Changed;
// Invoke the Changed event.
protected virtual void OnChanged(EventArgs e)
{
if (Changed != null)
Changed(this, e);
}
public MyObject(int myInt, string myString)
{
_myInt = myInt;
_myString = myString;
OnChanged(EventArgs.Empty);
}
private int _myInt;
public int MyInt
{
get { return _myInt; }
set { _myInt = value; OnChanged(EventArgs.Empty); }
}
private string _myString;
public string MyString
{
get { return _myString; }
set { _myString = value; OnChanged(EventArgs.Empty); ; }
}
}
class MyCollection
{
public List<MyObject> ObjectsList = new List<MyObject>();
public MyCollection()
{
// Add "eventChanged" to the Changed event on "List".
// ObjectsList<>.Changed += new ChangedEventHandler(ListChanged);
ObjectsList.Add(new MyObject(1, "One"));
ObjectsList.Add(new MyObject(2, "Two"));
ObjectsList.Add(new MyObject(3, "Three"));
}
// This will be called whenever the list changes.
private void ListChanged(object sender, EventArgs e)
{
Console.WriteLine("This is called when the event fires.");
}
}
}