In part 1 of this post, I explained the purpose of those wrapper classes I created, and why the structure is how it is. I’m making the source code of the library available with this post — use it as you see fit, but please note that I have done no production testing of this code, so don’t blame me if it breaks. The download is here: Sturm.CollectionWrapping.zip
Now how do you use that thing? Basically you use code like this:
BindingList<string> list = new BindingList<string>( );
BindingList<string> wrappedList = TypedListWrapper.CreateWrapper(list, propertyDescriptorCollection);
Now, depending on the type of list you wrap, the return value of the CreateWrapper method is actually of one of the following four types:
TypedListWrapperBindingListT
— this is used forBindingList<T>
derived collectionsTypedListWrapperIBindingList
— this is used for collections that implementIBindingList
, but are not derived fromBindingList<T>
TypedListWrapperIListT
— this is used for collections that implementIList<T>
TypedListWrapperIList
— for collections that implementIList
The selection is made in one of two ways. The first approach is based on method overloads that exist for the CreateWrapper
method. So as long as the compiler can find out what type you’re using, you’ll get the correct wrapper type that way.
The second approach uses an overload of the CreateWrapper
method that uses object
as the type of the collection. In this case, an algorithm runs that uses Reflection to find out in which category (of the above list) the given collection fits. This second approach seemed necessary as there are many situations when coding in .NET, where a collection type is obtained from some source that is not clearly typed (like a control’s DataSource
property, to name one simple example).
Finally, the parameter propertyDescriptorCollection
is of course just that — the collection of property descriptors that is returned by the ITypedList
method GetItemProperties
. There is a property called PropertyDescriptorCollection
on the wrapped collection type, so you can change the collection after the fact. Most of the methods and constructors also have other overloads — read the source to find out more about them. So, have fun with the library, I hope it’s useful. Let me know if you find any problems, if you have questions or suggestions for extensions.