After a simple transformation, the observablecollection can be added to any new Member (note that the existing member is replaced). An event is required for notification, you can also set whether to allow the new element to be added.
The principle is very simple. You can use the events related to the inotifycollectionchanged interface to determine the new element, initiate your own event notifications, and decide whether to delete the new element based on the event eventargs.
Code:
// + Using system. Collections. objectmodel;
// + Using system. Collections. Specialized;
Class myobserlist <t>: observablecollection <t>
{
// Inotifycollectionchanged collectionchanged event
Protected override void oncollectionchanged (yycollectionchangedeventargs E)
{
Base. oncollectionchanged (E );
If (E. Action = policycollectionchangedaction. Add | E. Action = policycollectionchangedaction. Replace)
{
VaR item = (t) E. newitems [0];
Onitemadded (New itemaddedeventargs <t> (item), E. newstartingindex );
}
}
// Events added to the element
Public event eventhandler <itemaddedeventargs <t> itemadded;
Protected virtual void onitemadded (itemaddedeventargs <t> E, int index)
{
VaR handler = This. itemadded;
If (handler! = NULL)
Handler (this, e );
If (E. iscancelled)
Removeat (INDEX );
}
}
Class itemaddedeventargs <t>: eventargs
{
// Target Element
Public t item {Get; private set ;}
// Whether to cancel the add operation. The default value is
Public bool iscancelled {Get; set ;}
Public itemaddedeventargs (T item)
{
Item = item;
}
}
For example, create a simple observablecollection and disable all even numbers from being added:
Static void main (string [] ARGs)
{
VaR list = new list <int> ();
VaR collec = new myobserlist <int> ();
Collec. itemadded + = collec_itemadded;
// Join successful
Collec. Add (1 );
// Do not join
Collec. Add (2 );
// Change 1 to 4. addition failed. At this time, collec does not contain any elements.
Collec [0] = 4;
Console. writeline ("count:" + collec. Count );
}
// Even numbers are not added
Static void collec_itemadded (Object sender, itemaddedeventargs <int> E)
{
If (E. Item % 2 = 0)
{
E. iscancelled = true;
Console. writeline ("{0} canceled", E. item );
}
Else
Console. writeline ("{0} added", E. item );
}
Output:
1 added
2 canceled
4 canceled
Count: 0