What it makes that collections are bindable? Is there common interface for List
, DataTable
with can bind to same contro开发者_如何学编程l?
To explain how List<T>
and DataTable
work (the footnote of the question), read the following but noting that:
List<T>
implementsIList
and has apublic T this[int index] {get;}
which is used for resolving metadataDataTable
implementsIListSource
, which provides the table's defaultDataView
; theDataView
implementsIList
, and implementsITypedList
to provide metadata
Collections bind in the following order:
- the source is tested for
IListSource
; if available theIList
is obtained viaGetList()
- otherwise the source is tested for
IList
; if unavailable an exception is thrown
then metadata for the IList
is queried:
- the
IList
is tested forITypedList
; if available this is used viaGetProperties
- the
IList
is tested for a public typed (non-object) indexer, i.e.public Foo this[int index] { get; }
- if found,Foo
is implied as the type and metadata obtained viaTypeDescriptor.GetProperties(Type)
- else the first item (if non-empty) is queried via
GetType()
for the type, and metadata obtained viaTypeDescriptor.GetProperties(Type)
we now have access to the items (IList
) and their metadata; additional support (optional) is provided via IBindingList
(provides 2-way binding and basic sorting etc), IBindingListView
(provides advanced sorting, filtering, etc), ICancelAddNew
and IRaiseItemChangedEvents
.
For most common scenarios (show data and push changes back) List<T>
is fine; if you need to show unrelated updates as they happen BindingList<T>
helps - but note that to support member level updates (as opposed to just add/remove/etc) the T
must implement INotifyPropertyChanged
For reference, "metadata" here means "a set of PropertyDescriptor
s" (1 per column/property), which provide access to the underlying data (when supplied with an object
), and information about the member itself (name, type, etc).
Most controls can bind to the IList interface.
http://msdn.microsoft.com/en-us/library/system.collections.ilist.aspx
IBindingList
精彩评论