Advanced ADO.NET Data Binding: Looking Behind the Scenes

Advanced ADO NET Data Binding Looking Behind the Scenes

The preceding section gave some of the flavor of ADO.NET data binding; we should more carefully describe what is happening behind the scenes here. After all, you might want to write your own code to set up data binding rather than relying on the code generated for you by the designer.

The first thing we need to do is describe what objects work together to bind data to controls. In the Excel data binding example, many objects are involved. There are the two controlsthe list object and the XML mapped rangethe dataset and the two data tables.

Each control implements IBindableComponent, so each control has a DataBindings property that returns an instance of ControlBindingsCollection. This object maintains a collection of Binding objects, one for each simple data binding. The collection is indexed by the name of the property, which has been simple-data-bound.

Each Binding object contains all the information necessary to describe the binding: what member of what data source is bound to what property of what control, how the data is to be formatted, and so on.

Binding Managers Manage Currency

One important member of the Binding object is the BindingManagerBase property. The binding manager is the object that actually does the work of the data binding: listening to changes in the data source and bound controls and ensuring that they stay synchronized.

The binding manager for data tables and other "list" data sources keeps track of the "currency" of the data source. If you bind a list to a control that displays a single datum, the control will display the current item as determined by the currency manager. (Because we'll almost always be talking about binding to list data sources, we use binding manager and currency manager interchangeably throughout.)

Most of the time, each binding source has exactly one currency manager associated with it; two controls bound to the same binding source share a currency manager and therefore share currency. In the event that you want to have two controls bound to a single binding source but with different currency, each control needs to have its own "binding context." A binding context is a collection that keeps track of pairs of binding sources and binding managers; within each context, every binding source has a unique binding manager, but two contexts can associate different managers with the same source, thereby keeping two or more currencies in one binding source.

In typical scenarios, there is only one binding context, so this point is largely moot. Even when you have only one, the binding context does have one use. When complex data binding, the binding context exposed by a list object lets you obtain the currency manager for the binding source.

Категории