BindingContext BindingContext BindingContext BindingContext Class

Definición

Administra la colección de objetos BindingManagerBase para cualquier objeto que herede de la clase Control.Manages the collection of BindingManagerBase objects for any object that inherits from the Control class.

public ref class BindingContext : System::Collections::ICollection
public class BindingContext : System.Collections.ICollection
type BindingContext = class
    interface ICollection
    interface IEnumerable
Public Class BindingContext
Implements ICollection
Herencia
BindingContextBindingContextBindingContextBindingContext
Implementaciones

Ejemplos

El ejemplo de código siguiente crea cuatro Binding objetos que se va a enlazar los cinco controles: un DateTimePicker y cuatro TextBox controles - a varios orígenes de datos.The following code example creates four Binding objects to bind five controls - a DateTimePicker and four TextBox controls - to several data sources. El BindingContext , a continuación, se utiliza para obtener el BindingManagerBase para cada origen de datos.The BindingContext is then used to get the BindingManagerBase for each data source.

void BindControls()
{
   /* Create two Binding objects for the first two TextBox 
         controls. The data-bound property for both controls 
         is the Text property. The data source is a DataSet 
         (ds). The data member is a navigation path in the form: 
         "TableName.ColumnName". */
   text1->DataBindings->Add( gcnew Binding( "Text",ds,"customers.custName" ) );
   text2->DataBindings->Add( gcnew Binding( "Text",ds,"customers.custID" ) );

   /* Bind the DateTimePicker control by adding a new Binding. 
         The data member of the DateTimePicker is a navigation path:
         TableName.RelationName.ColumnName string. */
   DateTimePicker1->DataBindings->Add( gcnew Binding( "Value",ds,"customers.CustToOrders.OrderDate" ) );

   /* Add event delegates for the Parse and Format events to a 
         new Binding object, and add the object to the third 
         TextBox control's BindingsCollection. The delegates 
         must be added before adding the Binding to the 
         collection; otherwise, no formatting occurs until 
         the Current object of the BindingManagerBase for 
         the data source changes. */
   Binding^ b = gcnew Binding( "Text",ds,"customers.custToOrders.OrderAmount" );
   b->Parse += gcnew ConvertEventHandler( this, &Form1::CurrencyStringToDecimal );
   b->Format += gcnew ConvertEventHandler( this, &Form1::DecimalToCurrencyString );
   text3->DataBindings->Add( b );

   // Get the BindingManagerBase for the Customers table. 
   bmCustomers = this->BindingContext[ ds,"Customers" ];

   /* Get the BindingManagerBase for the Orders table using the 
         RelationName. */
   bmOrders = this->BindingContext[ds, "customers.CustToOrders"];

   /* Bind the fourth TextBox control's Text property to the
      third control's Text property. */
   text4->DataBindings->Add( "Text", text3, "Text" );
}
protected void BindControls()
{
   /* Create two Binding objects for the first two TextBox 
      controls. The data-bound property for both controls 
      is the Text property. The data source is a DataSet 
      (ds). The data member is a navigation path in the form: 
      "TableName.ColumnName". */
   text1.DataBindings.Add(new Binding
   ("Text", ds, "customers.custName"));
   text2.DataBindings.Add(new Binding
   ("Text", ds, "customers.custID"));
   
   /* Bind the DateTimePicker control by adding a new Binding. 
      The data member of the DateTimePicker is a navigation path:
      TableName.RelationName.ColumnName string. */
   DateTimePicker1.DataBindings.Add(new 
   Binding("Value", ds, "customers.CustToOrders.OrderDate"));

   /* Add event delegates for the Parse and Format events to a 
      new Binding object, and add the object to the third 
      TextBox control's BindingsCollection. The delegates 
      must be added before adding the Binding to the 
      collection; otherwise, no formatting occurs until 
      the Current object of the BindingManagerBase for 
      the data source changes. */
      Binding b = new Binding
      ("Text", ds, "customers.custToOrders.OrderAmount");
   b.Parse+=new ConvertEventHandler(CurrencyStringToDecimal);
   b.Format+=new ConvertEventHandler(DecimalToCurrencyString);
   text3.DataBindings.Add(b);

   // Get the BindingManagerBase for the Customers table. 
   bmCustomers = this.BindingContext [ds, "Customers"];

   /* Get the BindingManagerBase for the Orders table using the 
      RelationName. */ 
   bmOrders = this.BindingContext[ds, "customers.CustToOrders"];

   /* Bind the fourth TextBox control's Text property to the
   third control's Text property. */
   text4.DataBindings.Add("Text", text3, "Text");
}

Protected Sub BindControls()

   ' Create two Binding objects for the first two TextBox 
   '   controls. The data-bound property for both controls 
   '   is the Text property. The data source is a DataSet 
   '   (ds). The data member is the string 
   '   "TableName.ColumnName".
   text1.DataBindings.Add(New Binding _
      ("Text", ds, "customers.custName"))
   text2.DataBindings.Add(New Binding _
      ("Text", ds, "customers.custID"))
   
   ' Bind the DateTimePicker control by adding a new Binding. 
   '   The data member of the DateTimePicker is a 
   '   TableName.RelationName.ColumnName string.
   DateTimePicker1.DataBindings.Add(New Binding _
      ("Value", ds, "customers.CustToOrders.OrderDate"))

   ' Add event delegates for the Parse and Format events to a 
   '   new Binding object, and add the object to the third 
   '   TextBox control's BindingsCollection. The delegates 
   '   must be added before adding the Binding to the 
   '   collection; otherwise, no formatting occurs until 
   '   the Current object of the BindingManagerBase for 
   '   the data source changes.
   Dim b As Binding = New Binding _
      ("Text", ds, "customers.custToOrders.OrderAmount")
   AddHandler b.Parse,  New ConvertEventHandler(AddressOf CurrencyStringToDecimal)      
   AddHandler b.Format, New ConvertEventHandler(AddressOf DecimalToCurrencyString)
   text3.DataBindings.Add(b)

   ' Get the BindingManagerBase for the Customers table.
   bmCustomers = Me.BindingContext(ds, "Customers")

   ' Get the BindingManagerBase for the Orders table using the 
   '   RelationName.
   bmOrders = Me.BindingContext(ds, "customers.CustToOrders")

   ' Bind the fourth TextBox control's Text property to the
   ' third control's Text property.
   text4.DataBindings.Add("Text", text3, "Text")

End Sub

Comentarios

Cada formulario de Windows tiene al menos una BindingContext objeto que administra el BindingManagerBase objetos para el formulario.Each Windows Form has at least one BindingContext object that manages the BindingManagerBase objects for the form. Porque el BindingManagerBase clase es abstracta, el tipo de valor devuelto de la Item[Object] propiedad sea un CurrencyManager o PropertyManager.Because the BindingManagerBase class is abstract, the return type of the Item[Object] property is either a CurrencyManager or a PropertyManager. Si el origen de datos es un objeto que puede devolver una sola propiedad (en lugar de una lista de objetos), el Type es un PropertyManager.If the data source is an object that can return only a single property (instead of a list of objects), the Type is a PropertyManager. Por ejemplo, si especifica un TextBox como origen de datos, un PropertyManager se devuelve.For example, if you specify a TextBox as the data source, a PropertyManager is returned. Por otro lado, si el origen de datos es un objeto que implementa IList o IBindingList, un CurrencyManager se devuelve.On the other hand, if the data source is an object that implements IList or IBindingList, a CurrencyManager is returned.

Para cada origen de datos en un formulario de Windows, hay una sola CurrencyManager o PropertyManager.For each data source on a Windows Form, there is a single CurrencyManager or PropertyManager. Dado que puede haber varios orígenes de datos asociados a un formulario de Windows, el BindingContext le permite recuperar un determinado CurrencyManager asociado con un origen de datos.Because there may be multiple data sources associated with a Windows Form, the BindingContext enables you to retrieve any particular CurrencyManager associated with a data source.

Nota

Cuando se usa el Item[Object] propiedad, el BindingContext crea un nuevo BindingManagerBase si aún no existe.When using the Item[Object] property, the BindingContext creates a new BindingManagerBase if one does not already exist. Esto puede provocar cierta confusión, como el objeto devuelto no puede administrar la lista (o cualquier lista) que desea.This can lead to some confusion, as the returned object may not manage the list (or any list) that you intend. Para impedir que se devuelva un no válido BindingManagerBase, utilice el Contains método para determinar si el destino BindingManagerBase ya existe.To prevent returning an invalid BindingManagerBase, use the Contains method to determine if the intended BindingManagerBase already exists.

Si usa un control contenedor, como un GroupBox, Panel, o TabControl, para contener los controles enlazados a datos, puede crear un BindingContext sólo para ese control contenedor y sus controles.If you use a container control, such as a GroupBox, Panel, or TabControl, to contain data-bound controls, you can create a BindingContext for just that container control and its controls. A continuación, cada parte del formulario se puede administrar mediante su propia BindingManagerBase.Then, each part of your form can be managed by its own BindingManagerBase. Consulte la BindingContext constructor para obtener más información acerca de cómo crear varios BindingManagerBase objetos para el mismo origen de datos.See the BindingContext constructor for more information about creating multiple BindingManagerBase objects for the same data source.

Si agrega un TextBox control a un formulario y un enlace a una columna de una tabla en un conjunto de datos, el control se comunica con el BindingContext de ese formulario.If you add a TextBox control to a form and bind it to a column of a table in a dataset, the control communicates with the BindingContext of that form. El BindingContext, en cambio, habla con específico del CurrencyManager para esa asociación de datos.The BindingContext, in turn, talks to the specific CurrencyManager for that data association. Si ha consultado el Position propiedad de la CurrencyManager, se informará de que el registro actual para el enlace de ese TextBox control.If you queried the Position property of the CurrencyManager, it would report the current record for the binding of that TextBox control. En el ejemplo de código siguiente, un TextBox está enlazado el FirstName columna de un Customers de tabla en el dataSet1 conjunto de datos a través de la BindingContext para el formulario está en.In the following code example, a TextBox control is bound to the FirstName column of a Customers table on the dataSet1 dataset through the BindingContext for the form it is on.

TextBox1.DataBindings.Add("Text", dataSet1, "Customers.FirstName")  
textBox1.DataBindings.Add("Text", dataSet1, "Customers.FirstName");  
textBox1->DataBindings->Add("Text", dataSet1, "Customers.FirstName");  

Puede agregar un segundo TextBox control (TextBox2) al formulario y enlazarlo a la LastName columna de la Customers tabla en el mismo conjunto de datos.You can add a second TextBox control (TextBox2) to the form and bind it to the LastName column of the Customers table in the same dataset. El BindingContext es consciente del primer enlace (TextBox1 a Customers.FirstName), por lo que usaría el mismo CurrencyManager, ya que ambos cuadros de texto están enlazados al mismo conjunto de datos (DataSet1).The BindingContext is aware of the first binding (TextBox1 to Customers.FirstName), so it would use the same CurrencyManager, as both text boxes are bound to the same dataset (DataSet1).

TextBox2.DataBindings.Add("Text", dataSet1, "Customers.LastName")  
textBox2.DataBindings.Add("Text", dataSet1, "Customers.LastName");  
textBox2->DataBindings->Add("Text", dataSet1, "Customers.LastName");  

Si enlaza TextBox2 a otro conjunto de datos, el BindingContext crea y administra un segundo CurrencyManager.If you bind TextBox2 to a different dataset, the BindingContext creates and manages a second CurrencyManager.

Es importante ser coherente sobre cómo establecer el DataSource y DisplayMember propiedades; de lo contrario, el BindingContext crea moneda varios administradores para el mismo conjunto de datos, lo que produce errores.It is important to be consistent about how you set the DataSource and DisplayMember properties; otherwise, the BindingContext creates multiple currency managers for the same dataset, which results in errors. El ejemplo de código siguiente muestra algunos ejemplos de cómo establecer las propiedades y sus asociados BindingContext objetos.The following code example shows a few ways to set the properties and their associated BindingContext objects. Puede establecer las propiedades mediante cualquiera de los métodos siguientes, siempre que sean coherentes en todo el código.You can set the properties using either of the following methods, as long as you are consistent throughout your code.

ComboBox1.DataSource = DataSet1  
ComboBox1.DisplayMember = "Customers.FirstName"  
Me.BindingContext(dataSet1, "Customers").Position = 1  
comboBox1.DataSource = DataSet1;  
comboBox1.DisplayMember = "Customers.FirstName";  
this.BindingContext[dataSet1, "Customers"].Position = 1;  
comboBox1->DataSource = dataSet1;  
comboBox1->DisplayMember = "Customers.FirstName";  
this->BindingContext->get_Item(dataSet1, "Customers")->Position = 1;  
ComboBox1.DataSource = DataSet1.Customers  
ComboBox1.DisplayMember = "FirstName"  
Me.BindingContext(dataSet1.Customers).Position = 1  
comboBox1.DataSource = DataSet1.Customers;  
comboBox1.DisplayMember = "FirstName";  
this.BindingContext[dataSet1.Customers].Position = 1;  
comboBox1->DataSource = dataSet1->Customers;  
comboBox1->DisplayMember = "FirstName";  
this->BindingContext->get_Item(dataSet1->Customers)->Position = 1;  

Nota

La mayoría de las aplicaciones de Windows Forms se enlazan mediante un BindingSource.Most Windows Forms applications bind through a BindingSource. El BindingSource componente encapsula una CurrencyManager y expone el CurrencyManager interfaz de programación.The BindingSource component encapsulates a CurrencyManager and exposes the CurrencyManager programming interface. Cuando se usa un BindingSource para el enlace, debe usar los miembros expuestos por el BindingSource para manipular "moneda" (es decir, Position) en lugar de recorrer el BindingContext.When using a BindingSource for binding, you should use the members exposed by the BindingSource to manipulate "currency" (that is, Position) rather than go through the BindingContext.

Constructores

BindingContext() BindingContext() BindingContext() BindingContext()

Inicializa una nueva instancia de la clase BindingContext.Initializes a new instance of the BindingContext class.

Propiedades

IsReadOnly IsReadOnly IsReadOnly IsReadOnly

Obtiene un valor que indica si la colección es de solo lectura.Gets a value indicating whether the collection is read-only.

Item[Object, String] Item[Object, String] Item[Object, String] Item[Object, String]

Obtiene un objeto BindingManagerBase asociado al origen de datos y miembro de datos especificados.Gets a BindingManagerBase that is associated with the specified data source and data member.

Item[Object] Item[Object] Item[Object] Item[Object]

Obtiene el objeto BindingManagerBase asociado al origen de datos especificado.Gets the BindingManagerBase that is associated with the specified data source.

Métodos

Add(Object, BindingManagerBase) Add(Object, BindingManagerBase) Add(Object, BindingManagerBase) Add(Object, BindingManagerBase)

Agrega a la colección el objeto BindingManagerBase asociado a un origen de datos específico.Adds the BindingManagerBase associated with a specific data source to the collection.

AddCore(Object, BindingManagerBase) AddCore(Object, BindingManagerBase) AddCore(Object, BindingManagerBase) AddCore(Object, BindingManagerBase)

Agrega a la colección el objeto BindingManagerBase asociado a un origen de datos específico.Adds the BindingManagerBase associated with a specific data source to the collection.

Clear() Clear() Clear() Clear()

Borra cualquier objeto BindingManagerBase de la colección.Clears the collection of any BindingManagerBase objects.

ClearCore() ClearCore() ClearCore() ClearCore()

Borra la colección.Clears the collection.

Contains(Object) Contains(Object) Contains(Object) Contains(Object)

Obtiene un valor que indica si BindingContext contiene el objeto BindingManagerBase asociado al origen de datos especificado.Gets a value indicating whether the BindingContext contains the BindingManagerBase associated with the specified data source.

Contains(Object, String) Contains(Object, String) Contains(Object, String) Contains(Object, String)

Obtiene un valor que indica si BindingContext contiene el objeto BindingManagerBase asociado al origen de datos y miembro de datos especificados.Gets a value indicating whether the BindingContext contains the BindingManagerBase associated with the specified data source and data member.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determina si el objeto especificado es igual al objeto actual.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Sirve como la función hash predeterminada.Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

Obtiene el Type de la instancia actual.Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Crea una copia superficial del objeto Object actual.Creates a shallow copy of the current Object.

(Inherited from Object)
OnCollectionChanged(CollectionChangeEventArgs) OnCollectionChanged(CollectionChangeEventArgs) OnCollectionChanged(CollectionChangeEventArgs) OnCollectionChanged(CollectionChangeEventArgs)

Genera el evento CollectionChanged.Raises the CollectionChanged event.

Remove(Object) Remove(Object) Remove(Object) Remove(Object)

Elimina el objeto BindingManagerBase asociado al origen de datos especificado.Deletes the BindingManagerBase associated with the specified data source.

RemoveCore(Object) RemoveCore(Object) RemoveCore(Object) RemoveCore(Object)

Quita el objeto BindingManagerBase asociado al origen de datos especificado.Removes the BindingManagerBase associated with the specified data source.

ToString() ToString() ToString() ToString()

Devuelve una cadena que representa el objeto actual.Returns a string that represents the current object.

(Inherited from Object)
UpdateBinding(BindingContext, Binding) UpdateBinding(BindingContext, Binding) UpdateBinding(BindingContext, Binding) UpdateBinding(BindingContext, Binding)

Asocia una clase Binding a un nuevo objeto BindingContext.Associates a Binding with a new BindingContext.

Eventos

CollectionChanged CollectionChanged CollectionChanged CollectionChanged

Siempre provoca NotImplementedException cuando se controla.Always raises a NotImplementedException when handled.

Implementaciones de interfaz explícitas

ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32)

Copia los elementos de la colección en la matriz especificada, empezando por el índice de la colección.Copies the elements of the collection into a specified array, starting at the collection index.

ICollection.Count ICollection.Count ICollection.Count ICollection.Count

Obtiene el número total de objetos CurrencyManager de la colección administrados por BindingContext.Gets the total number of CurrencyManager objects managed by the BindingContext.

ICollection.IsSynchronized ICollection.IsSynchronized ICollection.IsSynchronized ICollection.IsSynchronized

Obtiene un valor que indica si la colección está sincronizada.Gets a value indicating whether the collection is synchronized.

ICollection.SyncRoot ICollection.SyncRoot ICollection.SyncRoot ICollection.SyncRoot

Obtiene un objeto que se utiliza para la sincronización (seguridad para la ejecución de subprocesos).Gets an object to use for synchronization (thread safety).

IEnumerable.GetEnumerator() IEnumerable.GetEnumerator() IEnumerable.GetEnumerator() IEnumerable.GetEnumerator()

Obtiene un enumerador para la colección.Gets an enumerator for the collection.

Extension Methods

Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable)

Convierte los elementos de IEnumerable en el tipo especificado.Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable)

Filtra los elementos de IEnumerable en función de un tipo especificado.Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable)

Habilita la paralelización de una consulta.Enables parallelization of a query.

AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable)

Convierte una interfaz IEnumerable en IQueryable.Converts an IEnumerable to an IQueryable.

Se aplica a

Consulte también: