How can I fire an event before adding an item to a collection in C #?

I would like to do some processing before the item is added to the BindingList. I see that there is a ListChanged event, but it fires after adding an item. The AddingNew event is fired only when the AddNew method is called (and not the Add method). Has anyone done something like this before?

UPDATE:

I created the following classes, and when the Add method is called in IList, my new Add method starts. So, do I have a casting problem that I read elsewhere? If I remove the ISpecialCollection interface from the collection, my Add method will not be called. Can someone explain why this works differently? I have a problem with casting if I use ISpecialCollection <interface?

public interface ISpecialCollection<T> : IList<T>
{
}

public class SpecialCollection<T> : BindingList<T>, ISpecialCollection<T>
{
  public new void Add (T item)  
  {
    base.Add(item);    
  }
}

class Program
{
  static void Main(string[] args)
  {
    IList<ItemType> list = new SpecialCollection<ItemType>();
    list.Add(new ItemType());
  }
}
+5
7

BindingList.InsertItem (MSDN). Add, Insert, , . , base.InsertItem, .

+3

- Collection<T>. BCL, . , BindingList<T> List<T>, .

Collection<T> .

+3

- , ItemAdding ItemAdded

- ,

// class that inherits generic List and hides the add item
public class ListWithEvents<T> : List<T>
    {
        public event EventHandler ItemAdding;
        public event EventHandler ItemAdded;

        public new void Add(T item)
        {
            if (ItemAdding != null)
                ItemAdding(item, EventArgs.Empty);

            base.Add(item);

            if (ItemAdded != null)
                ItemAdded(item, EventArgs.Empty);

        }
    }

// Using the class
protected override void OnLoad(EventArgs e)
    {

        ListWithEvents<int> lstI = new ListWithEvents<int>();
        lstI.ItemAdded += new EventHandler(lstI_ItemAdded);
        lstI.ItemAdding += new EventHandler(lstI_ItemAdding);
    }

    void lstI_ItemAdding(object sender, EventArgs e)
    {
        throw new NotImplementedException();
    }

    void lstI_ItemAdded(object sender, EventArgs e)
    {
        throw new NotImplementedException();
    }
+2

- :

  public class PreProcessBindingList<T> : Collection<T>
    {   
        public AddingNewEventHandler AddingNew;

        public override void Add(T item)
        {
            PreProcess(item);
            base.Add(item);

            AddingNewEventHandler addingNew = this.AddingNew;
            if (addingNew != null)
            {
                addingNew(this, new AddingNewEventArgs(item));
            }
        }
    }
+1

: Collection<T> InsertItem. base.InsertItem.

0

C5. C5 , , , , , .

, C5- System.Collection.Generic ICollection IList, , , , . a SCG.ICollection.

EDIT: ; , , , , , ..

0

ObservableCollection. , , . , WPF, ASP.NET.

-1

All Articles