BindingContext Clase

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
BindingContext
Implementaciones

Ejemplos

En el ejemplo de código siguiente se crean cuatro objetos Binding para enlazar cinco controles: un DateTimePicker y cuatro controles TextBox 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. A continuación, el BindingContext se utiliza para obtener el BindingManagerBase de 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 Windows Forms tiene al menos un objeto BindingContext que administra los objetos BindingManagerBase para el formulario.Each Windows Form has at least one BindingContext object that manages the BindingManagerBase objects for the form. Dado que la clase BindingManagerBase es abstracta, el tipo de valor devuelto de la propiedad Item[] es un CurrencyManager o un PropertyManager.Because the BindingManagerBase class is abstract, the return type of the Item[] property is either a CurrencyManager or a PropertyManager. Si el origen de datos es un objeto que solo puede devolver una 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, se devuelve un PropertyManager.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, se devuelve un CurrencyManager.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 Windows Forms, 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 Windows Form, el BindingContext le permite recuperar cualquier CurrencyManager determinado asociado a 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

Al utilizar la propiedad Item[], el BindingContext crea un nuevo BindingManagerBase si todavía no existe uno.When using the Item[] property, the BindingContext creates a new BindingManagerBase if one does not already exist. Esto puede llevar a confusión, ya que el objeto devuelto puede no administrar la lista (o cualquier lista) que desee.This can lead to some confusion, as the returned object may not manage the list (or any list) that you intend. Para evitar que se devuelva un BindingManagerBaseno válido, use el método Contains para determinar si el BindingManagerBase deseado ya existe.To prevent returning an invalid BindingManagerBase, use the Contains method to determine if the intended BindingManagerBase already exists.

Si utiliza un control contenedor, como un GroupBox, Panelo TabControl, para contener controles enlazados a datos, puede crear un BindingContext solo 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 puede administrarse por su propio BindingManagerBase.Then, each part of your form can be managed by its own BindingManagerBase. Vea el constructor BindingContext para obtener más información sobre la creación de varios objetos BindingManagerBase 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 control TextBox a un formulario y lo enlaza a una columna de una tabla en un conjunto de DataSet, el control se comunica con el BindingContext de dicho 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, a su vez, se comunica con el CurrencyManager específico para esa asociación de datos.The BindingContext, in turn, talks to the specific CurrencyManager for that data association. Si ha consultado la propiedad Position del CurrencyManager, notificaría el registro actual para el enlace de ese control de TextBox.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, se enlaza un control TextBox a la columna FirstName de una tabla Customers en el conjunto de elementos dataSet1 a través del BindingContext del formulario en el que se encuentra.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 control TextBox (TextBox2) al formulario y enlazarlo a la columna LastName de la tabla Customers en el mismo conjunto de los mismos.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 DataSet (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 un conjunto de diferentes, 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 el modo de establecer las propiedades DataSource y DisplayMember; de lo contrario, el BindingContext crea varios administradores de moneda para el mismo conjunto de resultados, 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. En el ejemplo de código siguiente se muestran algunas maneras de establecer las propiedades y sus objetos BindingContext asociados.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 sea coherente 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 Windows Forms enlazan a través de un BindingSource.Most Windows Forms applications bind through a BindingSource. El componente de BindingSource encapsula un CurrencyManager y expone la interfaz de programación de CurrencyManager.The BindingSource component encapsulates a CurrencyManager and exposes the CurrencyManager programming interface. Al utilizar una BindingSource para el enlace, debe usar los miembros expuestos por el BindingSource para manipular "Currency" (es decir, Position) en lugar de pasar por 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()

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

Propiedades

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]

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]

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)

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)

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()

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

ClearCore()

Borra la colección.Clears the collection.

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)

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)

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

(Heredado de Object)
GetHashCode()

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

(Heredado de Object)
GetType()

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

(Heredado de Object)
MemberwiseClone()

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

(Heredado de Object)
OnCollectionChanged(CollectionChangeEventArgs)

Inicia el evento CollectionChanged.Raises the CollectionChanged event.

Remove(Object)

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

RemoveCore(Object)

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

ToString()

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

(Heredado de Object)
UpdateBinding(BindingContext, Binding)

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

Eventos

CollectionChanged

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

Implementaciones de interfaz explícitas

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

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

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

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()

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

Métodos de extensión

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)

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)

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

AsQueryable(IEnumerable)

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

Se aplica a

Consulte también: