class Foo(){
public List<string> SomeCollection;
}
I need to implement an event which can fires when something added or removed from the Collection. How to do this?
class Foo(){
public List<string> SomeCollection;
}
I need to implement an event which can fires when something added or removed from the Collection. How to do this?
You might take a look at this tutorial on making your own custom events.
You can do this by using an ObservableCollection instead of a List.
Take a look at the BindingList
and ObservableCollection
classes (in the System.ComponentModel
and System.Collections.ObjectModel
namespaces respectively) - either one should do the job well for you.
Note that the two classes generally provide the same functionality, but they do differ slightly. BindingList
is typically more suitable for data-binding/UI purposes (hence it's name), since it allows the option to cancel updates and such. However, ObservableCollection
is possibly more appropiate in your case, since you're just interested in being notified of changes (it would seem), and the class was designed purely from that perspective. The fact that they exist in very different namespaces sort of hints at this. If you want the precise details on the similarities and differences, I recommend you inspect the linked MSDN docs.
List<T>
has no notification support. You could look at BindingList<T>
, which has events - or Collection<T>
, which can be inherited with override methods.
If you want to expose the event at the Foo
level, perhaps something like below - but it may be easier to leave it on the list:
class Foo{
public event EventHandler ListChanged;
private readonly BindingList<string> list;
public Foo() {
list = new BindingList<string>();
list.ListChanged += list_ListChanged;
}
void list_ListChanged(object sender, ListChangedEventArgs e) {
EventHandler handler = ListChanged;
if (handler != null) handler(this, EventArgs.Empty);
}
public IList<string> SomeCollection {get {return list;}}
}
basic one...
here is a good link
public class Foo
{
private List<string> _SomeCollection;
public event EventHandler Added;
public void Add(string item)
{
SomCollection.Add(item);
OnAdd();
}
private void OnAdd()
{
if (Added != null)
{
Added.Invoke(this, EventArgs.Empty);
}
}
}