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

En el ejemplo de código siguiente Binding se crean cuatro objetos para enlazar DateTimePicker cinco controles TextBox -a y cuatro 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. A continuación, BindingManagerBase seutilizaparaobtenerelparacadaBindingContext 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 BindingContext un objeto que administra BindingManagerBase los objetos del formulario.Each Windows Form has at least one BindingContext object that manages the BindingManagerBase objects for the form. Dado que BindingManagerBase la clase es abstracta, el tipo de valor Item[Object] devuelto de la CurrencyManager propiedad PropertyManageres o.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 solo puede devolver una propiedad (en lugar de una lista de objetos), Type es una. PropertyManagerIf 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 TextBox como origen de datos 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, 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 de un Windows Form, hay un único 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, BindingContext le permite recuperar CurrencyManager cualquier objeto 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 Item[Object] propiedad 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 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 no Contains válido BindingManagerBase, use el método para BindingManagerBase determinar si el previsto ya existe.To prevent returning an invalid BindingManagerBase, use the Contains method to determine if the intended BindingManagerBase already exists.

Si utiliza un GroupBoxcontrol contenedor, como, Panelo TabControl, para contener controles enlazados a datos, puede crear un BindingContext para solo 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. Después, cada parte del formulario se puede administrar por sí mismo BindingManagerBase.Then, each part of your form can be managed by its own BindingManagerBase. Vea el BindingContext constructor para obtener más información sobre la BindingManagerBase creación de varios 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 lo enlaza a una columna de una tabla en un conjunto de DataSet, el control se comunica con BindingContext el 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. A su vez, se comunica con el específico CurrencyManager para esa asociación de datos. BindingContextThe BindingContext, in turn, talks to the specific CurrencyManager for that data association. Si ha consultado Position la propiedad CurrencyManagerde, notificaría 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, TextBox se enlaza un control a FirstName la columna dataSet1 de Customers una tabla del conjunto de elementos BindingContext a través de para el 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 TextBox agregar un segundo control (TextBox2) al formulario y enlazarlo a la LastName columna de la Customers tabla 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. Customers.FirstName CurrencyManagerDataSet1Es consciente del primer enlace (TextBox1 hasta), por lo que usaría el mismo, ya que ambos cuadros de texto están enlazados al mismo conjunto de tipos (). BindingContextThe 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 se enlaza TextBox2 a un conjunto de diferentes 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 las DataSource BindingContext propiedades y DisplayMember ; de lo contrario, crea varios administradores de moneda para el mismo conjunto de resultados, lo que provoca 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 BindingContext sus objetos 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 BindingSourceenlazan a través de.Most Windows Forms applications bind through a BindingSource. El BindingSource componente encapsula un CurrencyManager y expone la interfaz de CurrencyManager programación.The BindingSource component encapsulates a CurrencyManager and exposes the CurrencyManager programming interface. Al usar un BindingSource para el enlace, debe usar los miembros expuestos BindingSource por para manipular "Currency" (es decir, Position) en lugar de ir a través de 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.

Métodos de extensión

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: