BindingContext Classe

Definizione

Gestisce la raccolta di BindingManagerBase oggetti per qualsiasi oggetto che eredita dalla Control classe .

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
Ereditarietà
BindingContext
Implementazioni

Esempio

Nell'esempio di codice seguente vengono creati quattro Binding oggetti per associare cinque controlli, ovvero un DateTimePicker controllo e quattro TextBox controlli, a diverse origini dati. Viene BindingContext quindi usato per ottenere l'oggetto BindingManagerBase per ogni origine dati.

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

Commenti

Ogni Windows Form include almeno un oggetto BindingContext che gestisce gli oggetti BindingManagerBase per il form. Poiché la BindingManagerBase classe è astratta, il tipo restituito della Item[] proprietà è o CurrencyManager .PropertyManager Se l'origine dati è un oggetto che può restituire solo una singola proprietà (anziché un elenco di oggetti), è Type .PropertyManager Ad esempio, se si specifica un TextBox oggetto come origine dati, viene restituito un oggetto PropertyManager . D'altra parte, se l'origine dati è un oggetto che implementa IList o IBindingList, viene restituito un CurrencyManager oggetto .

Per ogni origine dati in un modulo di Windows è presente un singolo CurrencyManager o PropertyManager. Poiché possono essere presenti più origini dati associate a un modulo Windows, l'BindingContext consente di recuperare qualsiasi particolare CurrencyManager associato a un'origine dati.

Note

Quando si utilizza la Item[] proprietà , crea BindingContext un nuovo BindingManagerBase oggetto se non esiste già. Ciò può causare confusione, poiché l'oggetto restituito potrebbe non gestire l'elenco (o qualsiasi elenco) previsto. Per impedire la restituzione di un oggetto non valido BindingManagerBase, utilizzare il Contains metodo per determinare se l'oggetto previsto BindingManagerBase esiste già.

Se si usa un controllo contenitore, ad esempio , GroupBoxPanelo TabControl, per contenere controlli associati a dati, è possibile creare un BindingContext oggetto solo per il controllo contenitore e i relativi controlli. Quindi, ogni parte del form può essere gestita da un proprio BindingManagerBaseoggetto . Per altre informazioni sulla creazione di più BindingManagerBase oggetti per la stessa origine dati, vedere il BindingContext costruttore.

Se si aggiunge un TextBox controllo a una maschera e lo si associa a una colonna di una tabella in un set di dati, il controllo comunica con l'oggetto BindingContext di tale modulo. A BindingContextsua volta, comunica con l'associazione di dati specifica CurrencyManager . Se si esegue una query sulla Position proprietà di CurrencyManager, verrà restituito il record corrente per l'associazione di tale TextBox controllo. Nell'esempio di codice seguente, un TextBox controllo viene associato alla FirstName colonna di una Customers tabella nel dataSet1 set di dati tramite per BindingContext il modulo su cui si trova.

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

È possibile aggiungere un secondo TextBox controllo (TextBox2) al form e associarlo alla LastName colonna della Customers tabella nello stesso set di dati. BindingContext è a conoscenza del primo binding (TextBox1 a Customers.FirstName), quindi userebbe lo stesso CurrencyManager, perché entrambe le caselle di testo sono associate allo stesso set di dati (DataSet1).

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

Se si esegue il binding TextBox2 a un set di dati diverso, crea BindingContext e gestisce un secondo CurrencyManager.

È importante essere coerenti sulla modalità di impostazione delle DataSource proprietà e DisplayMember . In caso contrario, BindingContext crea più gestori di valuta per lo stesso set di dati, che genera errori. Nell'esempio di codice seguente vengono illustrati alcuni modi per impostare le proprietà e i relativi oggetti associati BindingContext . È possibile impostare le proprietà usando uno dei metodi seguenti, purché sia coerente in tutto il codice.

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.Customers
ComboBox1.DisplayMember = "FirstName"
Me.BindingContext(dataSet1.Customers).Position = 1
comboBox1.DataSource = DataSet1.Customers;
comboBox1.DisplayMember = "FirstName";
this.BindingContext[dataSet1.Customers].Position = 1;

Note

La maggior parte delle applicazioni Windows Forms viene associata tramite un BindingSource. Il BindingSource componente incapsula un CurrencyManager oggetto ed espone l'interfaccia CurrencyManager di programmazione. Quando si usa un BindingSource oggetto per l'associazione, è consigliabile usare i membri esposti da BindingSource per modificare la "valuta", ovvero Position, anziché passare attraverso .BindingContext

Costruttori

Nome Descrizione
BindingContext()

Inizializza una nuova istanza della classe BindingContext.

Proprietà

Nome Descrizione
IsReadOnly

Ottiene un valore che indica se l'insieme è di sola lettura.

Item[Object, String]

Ottiene un BindingManagerBase oggetto associato all'origine dati e al membro dati specificato.

Item[Object]

Ottiene l'oggetto BindingManagerBase associato all'origine dati specificata.

Metodi

Nome Descrizione
Add(Object, BindingManagerBase)

Aggiunge l'oggetto associato a un'origine BindingManagerBase dati specifica alla raccolta.

AddCore(Object, BindingManagerBase)

Aggiunge l'oggetto associato a un'origine BindingManagerBase dati specifica alla raccolta.

Clear()

Cancella l'insieme di oggetti BindingManagerBase .

ClearCore()

Cancella la raccolta.

Contains(Object, String)

Ottiene un valore che indica se contiene l'oggetto BindingContext associato all'origine BindingManagerBase dati e al membro dati specificato.

Contains(Object)

Ottiene un valore che indica se contiene BindingContext l'oggetto BindingManagerBase associato all'origine dati specificata.

Equals(Object)

Determina se l'oggetto specificato è uguale all'oggetto corrente.

(Ereditato da Object)
GetHashCode()

Funge da funzione hash predefinita.

(Ereditato da Object)
GetType()

Ottiene il Type dell'istanza corrente.

(Ereditato da Object)
MemberwiseClone()

Crea una copia superficiale del Objectcorrente.

(Ereditato da Object)
OnCollectionChanged(CollectionChangeEventArgs)

Genera l'evento CollectionChanged.

Remove(Object)

Elimina l'oggetto BindingManagerBase associato all'origine dati specificata.

RemoveCore(Object)

Rimuove l'oggetto BindingManagerBase associato all'origine dati specificata.

ToString()

Restituisce una stringa che rappresenta l'oggetto corrente.

(Ereditato da Object)
UpdateBinding(BindingContext, Binding)

Associa un oggetto Binding a un nuovo BindingContextoggetto .

Eventi

Nome Descrizione
CollectionChanged

Genera sempre un oggetto NotImplementedException quando gestito.

Implementazioni dell'interfaccia esplicita

Nome Descrizione
ICollection.CopyTo(Array, Int32)

Copia gli elementi della raccolta in una matrice specificata, a partire dall'indice della raccolta.

ICollection.Count

Ottiene il numero totale di CurrencyManager oggetti gestiti da BindingContext.

ICollection.IsSynchronized

Ottiene un valore che indica se la raccolta è sincronizzata.

ICollection.SyncRoot

Ottiene un oggetto da utilizzare per la sincronizzazione (thread safety).

IEnumerable.GetEnumerator()

Ottiene un enumeratore per la raccolta.

Metodi di estensione

Nome Descrizione
AsParallel(IEnumerable)

Abilita la parallelizzazione di una query.

AsQueryable(IEnumerable)

Converte un IEnumerable in un IQueryable.

Cast<TResult>(IEnumerable)

Esegue il cast degli elementi di un IEnumerable al tipo specificato.

OfType<TResult>(IEnumerable)

Filtra gli elementi di un IEnumerable in base a un tipo specificato.

Si applica a

Vedi anche