Special C # Event Handlers

If I have a property:

public list<String> names { get; set; } 

How can I generate and handle a custom event for arguments called "onNamesChanged" when the name is added to the list?

+7
c # properties event-handling
source share
6 answers

You should check out System.ComponentModel.BindingList , specifically the ListChanged Event .

+10
source share

A BindingList is most likely your best bet, as it has built-in change tracking and many existing events that you can use. The following is an example of providing a custom event to add, which is dispatched to the BindingList event.

 class Example { private BindingList<string> m_names = new BindingList<string>(); public IEnumerable<string> Names { get { return m_names; } } public event AddingNewEventHandler NamesAdded { add { m_names.AddingNew += value; } remove { m_names.AddingNew -= value; } } public void Add(string name) { m_names.Add(name); } } 
+13
source share

One alternative to the BindingList ObservableCollection is in this case you want to subscribe to your own CollectionChanged event handler and fire your event depending on the action.

+10
source share

David Mohondro demonstrates one approach; another option is to inherit from Collection <T> and override the various methods:

 class Foo {} class FooCollection : Collection<Foo> { protected override void InsertItem(int index, Foo item) { // your code... base.InsertItem(index, item); } protected override void SetItem(int index, Foo item) { // your code... base.SetItem(index, item); } // etc } 

Finally, you can create your own list (IList, IList <T>) from the first principles - a lot of work, little use.

0
source share

An unorthodox approach can use an AOP structure such as PostSharp to β€œtwist” a handler before / after calling an accessory that fires an event.

You create an external class that contains the preliminary and / or mail processing code for accessing your property, check if the property value has changed between pre and post and will raise an event.

Remember that taking a value for comparison (inside the code of your handler), you can end up in an infinite loop (you call a property accessory that calls the AOP handler, which calls the accessor, etc.), so you may need to think about a class, containing this property to get the support field.

0
source share

You do not need to set the list directly as a property and, possibly, implement the IList class or some of them, then you have an event handler in the Add () method.

-one
source share

All Articles