Бөлісу құралы:


ControlBindingsCollection Класс

Определение

Представляет коллекцию привязок данных для элемента управления.

public ref class ControlBindingsCollection : System::Windows::Forms::BindingsCollection
[System.ComponentModel.TypeConverter("System.Windows.Forms.Design.ControlBindingsConverter, System.Design, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
public class ControlBindingsCollection : System.Windows.Forms.BindingsCollection
[System.ComponentModel.TypeConverter("System.Windows.Forms.Design.ControlBindingsConverter, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
public class ControlBindingsCollection : System.Windows.Forms.BindingsCollection
[System.ComponentModel.TypeConverter("System.Windows.Forms.Design.ControlBindingsConverter, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
public class ControlBindingsCollection : System.Windows.Forms.BindingsCollection
[<System.ComponentModel.TypeConverter("System.Windows.Forms.Design.ControlBindingsConverter, System.Design, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")>]
type ControlBindingsCollection = class
    inherit BindingsCollection
[<System.ComponentModel.TypeConverter("System.Windows.Forms.Design.ControlBindingsConverter, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")>]
type ControlBindingsCollection = class
    inherit BindingsCollection
[<System.ComponentModel.TypeConverter("System.Windows.Forms.Design.ControlBindingsConverter, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")>]
type ControlBindingsCollection = class
    inherit BindingsCollection
Public Class ControlBindingsCollection
Inherits BindingsCollection
Наследование
Атрибуты

Примеры

В следующем примере кода объекты добавляются Binding в ControlBindingsCollection пять элементов управления: четыре TextBox элемента управления и DateTimePicker элемент управления. Доступ ControlBindingsCollection осуществляется через DataBindings свойство Control класса.

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 the navigation path: 
         TableName.ColumnName. */
      textBox1->DataBindings->Add( gcnew Binding(
         "Text",ds,"customers.custName" ) );
      textBox2->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. */
      DateTimePicker1->DataBindings->Add( gcnew Binding(
         "Value",ds,"customers.CustToOrders.OrderDate" ) );
      
      /* Create a new Binding using the DataSet and a 
         navigation path(TableName.RelationName.ColumnName).
         Add event delegates for the Parse and Format events to 
         the 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 );
      textBox3->DataBindings->Add( b );
      
      /*Bind the fourth TextBox to the Value of the 
         DateTimePicker control. This demonstates how one control
         can be data-bound to another.*/
      textBox4->DataBindings->Add( "Text", DateTimePicker1, "Value" );
      
      // Get the BindingManagerBase for the textBox4 Binding.
      BindingManagerBase^ bmText = this->BindingContext[
         DateTimePicker1 ];
      
      /* Print the Type of the BindingManagerBase, which is 
         a PropertyManager because the data source
         returns only a single property value. */
      Console::WriteLine( bmText->GetType() );
      
      // Print the count of managed objects, which is one.
      Console::WriteLine( bmText->Count );
      
      // Get the BindingManagerBase for the Customers table. 
      bmCustomers = this->BindingContext[ds, "Customers"];
      
      /* Print the Type and count of the BindingManagerBase.
         Because the data source inherits from IBindingList,
         it is a RelatedCurrencyManager (a derived class of
         CurrencyManager). */
      Console::WriteLine( bmCustomers->GetType() );
      Console::WriteLine( bmCustomers->Count );
      
      /* Get the BindingManagerBase for the Orders of the current
         customer using a navigation path: TableName.RelationName. */
      bmOrders = this->BindingContext[ds, "customers.CustToOrders"];
   }
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 the navigation path: 
   TableName.ColumnName. */
   textBox1.DataBindings.Add(new Binding
   ("Text", ds, "customers.custName"));
   textBox2.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. */
   DateTimePicker1.DataBindings.Add(new 
   Binding("Value", ds, "customers.CustToOrders.OrderDate"));

   /* Create a new Binding using the DataSet and a 
   navigation path(TableName.RelationName.ColumnName).
   Add event delegates for the Parse and Format events to 
   the 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);
   textBox3.DataBindings.Add(b);

   /*Bind the fourth TextBox to the Value of the 
   DateTimePicker control. This demonstates how one control
   can be data-bound to another.*/
   textBox4.DataBindings.Add("Text", DateTimePicker1,"Value");

   // Get the BindingManagerBase for the textBox4 Binding.
   BindingManagerBase bmText = this.BindingContext
   [DateTimePicker1];

   /* Print the Type of the BindingManagerBase, which is 
   a PropertyManager because the data source
   returns only a single property value. */
   Console.WriteLine(bmText.GetType().ToString());

   // Print the count of managed objects, which is one.
   Console.WriteLine(bmText.Count);

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

   /* Print the Type and count of the BindingManagerBase.
   Because the data source inherits from IBindingList,
   it is a RelatedCurrencyManager (a derived class of
   CurrencyManager). */
   Console.WriteLine(bmCustomers.GetType().ToString());
   Console.WriteLine(bmCustomers.Count);
   
   /* Get the BindingManagerBase for the Orders of the current
   customer using a navigation path: TableName.RelationName. */ 
   bmOrders = this.BindingContext[ds, "customers.CustToOrders"];
}
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 navigation path: 
    ' TableName.ColumnName. 
    textBox1.DataBindings.Add _
       (New Binding("Text", ds, "customers.custName"))
    textBox2.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. 
    DateTimePicker1.DataBindings.Add _
       (New Binding("Value", ds, "customers.CustToOrders.OrderDate"))
    
    ' Create a new Binding using the DataSet and a 
    ' navigation path(TableName.RelationName.ColumnName).
    ' Add event delegates for the Parse and Format events to 
    ' the 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 New Binding("Text", ds, "customers.custToOrders.OrderAmount")
    AddHandler b.Parse, AddressOf CurrencyStringToDecimal
    AddHandler b.Format, AddressOf DecimalToCurrencyString
    textBox3.DataBindings.Add(b)
    
    ' Bind the fourth TextBox to the Value of the 
    ' DateTimePicker control. This demonstates how one control
    ' can be data-bound to another.
    textBox4.DataBindings.Add("Text", DateTimePicker1, "Value")
    
    ' Get the BindingManagerBase for the textBox4 Binding.
    Dim bmText As BindingManagerBase = Me.BindingContext(DateTimePicker1)
    
    ' Print the Type of the BindingManagerBase, which is 
    ' a PropertyManager because the data source
    ' returns only a single property value. 
    Console.WriteLine(bmText.GetType().ToString())
    
    ' Print the count of managed objects, which is one.
    Console.WriteLine(bmText.Count)
    
    ' Get the BindingManagerBase for the Customers table. 
    bmCustomers = Me.BindingContext(ds, "Customers")
    
    ' Print the Type and count of the BindingManagerBase.
    ' Because the data source inherits from IBindingList,
    ' it is a RelatedCurrencyManager (a derived class of
    ' CurrencyManager). 
    Console.WriteLine(bmCustomers.GetType().ToString())
    Console.WriteLine(bmCustomers.Count)
    
    ' Get the BindingManagerBase for the Orders of the current
    ' customer using a navigation path: TableName.RelationName. 
    bmOrders = Me.BindingContext(ds, "customers.CustToOrders")
End Sub

Комментарии

Простая привязка данных выполняется путем добавления Binding объектов в объект ControlBindingsCollection. Любой объект, наследуемый от Control класса, может получить доступ к ControlBindingsCollection свойству DataBindings . Список элементов управления Windows, поддерживающих привязку данных, см. в Binding классе.

Содержит ControlBindingsCollection стандартные методы сбора, такие как Add, Clearи Remove.

Чтобы получить элемент управления, к которому ControlBindingsCollection принадлежит, используйте Control свойство.

Конструкторы

Имя Описание
ControlBindingsCollection(IBindableComponent)

Инициализирует новый экземпляр ControlBindingsCollection класса с указанным привязываемым элементом управления.

Свойства

Имя Описание
BindableComponent

IBindableComponent Возвращает коллекцию привязок.

Control

Возвращает элемент управления, к которому принадлежит коллекция.

Count

Возвращает общее количество привязок в коллекции.

(Унаследовано от BindingsCollection)
DefaultDataSourceUpdateMode

Возвращает или задает значение по умолчанию DataSourceUpdateMode для Binding коллекции.

IsReadOnly

Возвращает значение, указывающее, доступна ли коллекция только для чтения.

(Унаследовано от BaseCollection)
IsSynchronized

Возвращает значение, указывающее, синхронизирован ли доступ к ней ICollection .

(Унаследовано от BaseCollection)
Item[Int32]

Возвращает указанный Binding индекс.

(Унаследовано от BindingsCollection)
Item[String]

Возвращает указанное Binding именем свойства элемента управления.

List

Возвращает привязки в коллекции в качестве объекта.

(Унаследовано от BindingsCollection)
SyncRoot

Получает объект, который можно использовать для синхронизации доступа к объекту BaseCollection.

(Унаследовано от BaseCollection)

Методы

Имя Описание
Add(Binding)

Добавляет указанный Binding в коллекцию.

Add(String, Object, String, Boolean, DataSourceUpdateMode, Object, String, IFormatProvider)

Создает привязку, которая привязывает указанное свойство элемента управления к указанному элементу данных указанного источника данных, при необходимости включив форматирование с указанной строкой формата, распространяя значения в источник данных на основе указанного параметра обновления, устанавливая свойство на указанное значение при DBNull возврате из источника данных, установив указанный поставщик формата. и добавление привязки в коллекцию.

Add(String, Object, String, Boolean, DataSourceUpdateMode, Object, String)

Создает привязку, которая привязывает указанное свойство элемента управления к указанному элементу данных указанного источника данных, при необходимости позволяя форматирование с указанной строкой формата, распространяя значения в источник данных на основе указанного параметра обновления, устанавливая свойство на указанное значение при DBNull возврате из источника данных и добавляя привязку в коллекцию.

Add(String, Object, String, Boolean, DataSourceUpdateMode, Object)

Создает привязку, которая привязывает указанное свойство элемента управления к указанному элементу данных указанного источника данных, при необходимости позволяя форматирование, распространяя значения в источник данных на основе указанного параметра обновления, устанавливая свойство на указанное значение при DBNull возврате из источника данных и добавляя привязку в коллекцию.

Add(String, Object, String, Boolean, DataSourceUpdateMode)

Создает привязку, которая привязывает указанное свойство элемента управления к указанному элементу данных указанного источника данных, при необходимости включает форматирование, распространяет значения в источник данных на основе указанного параметра обновления и добавляет привязку в коллекцию.

Add(String, Object, String, Boolean)

Создает привязку с указанным именем свойства элемента управления, источником данных, элементом данных и сведениями о том, включено ли форматирование, и добавляет привязку в коллекцию.

Add(String, Object, String)

Создает указанное Binding имя свойства элемента управления, источник данных и элемент данных и добавляет его в коллекцию.

AddCore(Binding)

Добавляет привязку в коллекцию.

Clear()

Очищает коллекцию любых привязок.

ClearCore()

Очищает привязки в коллекции.

CopyTo(Array, Int32)

Копирует все элементы текущего одномерного в указанный одномерный ArrayArray индекс, начиная с указанного целевого Array индекса.

(Унаследовано от BaseCollection)
CreateObjRef(Type)

Создает объект, содержащий все соответствующие сведения, необходимые для создания прокси-сервера, используемого для взаимодействия с удаленным объектом.

(Унаследовано от MarshalByRefObject)
Equals(Object)

Определяет, равен ли указанный объект текущему объекту.

(Унаследовано от Object)
GetEnumerator()

Возвращает объект, который позволяет выполнять итерацию между элементами коллекции.

(Унаследовано от BaseCollection)
GetHashCode()

Служит хэш-функцией по умолчанию.

(Унаследовано от Object)
GetLifetimeService()
Устаревшие..

Извлекает текущий объект службы времени существования, который управляет политикой времени существования для этого экземпляра.

(Унаследовано от MarshalByRefObject)
GetType()

Возвращает Type текущего экземпляра.

(Унаследовано от Object)
InitializeLifetimeService()
Устаревшие..

Получает объект службы времени существования для управления политикой времени существования для этого экземпляра.

(Унаследовано от MarshalByRefObject)
MemberwiseClone()

Создает неглубокую копию текущей Object.

(Унаследовано от Object)
MemberwiseClone(Boolean)

Создает неглубокую копию текущего MarshalByRefObject объекта.

(Унаследовано от MarshalByRefObject)
OnCollectionChanged(CollectionChangeEventArgs)

Вызывает событие CollectionChanged.

(Унаследовано от BindingsCollection)
OnCollectionChanging(CollectionChangeEventArgs)

Вызывает событие CollectionChanging.

(Унаследовано от BindingsCollection)
Remove(Binding)

Удаляет указанный Binding из коллекции.

RemoveAt(Int32)

Удаляет указанный Binding индекс.

RemoveCore(Binding)

Удаляет указанную привязку из коллекции.

ShouldSerializeMyAll()

Возвращает значение, указывающее, следует ли сериализовать коллекцию.

(Унаследовано от BindingsCollection)
ToString()

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)

События

Имя Описание
CollectionChanged

Происходит при изменении коллекции.

(Унаследовано от BindingsCollection)
CollectionChanging

Происходит при изменении коллекции.

(Унаследовано от BindingsCollection)

Методы расширения

Имя Описание
AsParallel(IEnumerable)

Включает параллелизацию запроса.

AsQueryable(IEnumerable)

Преобразует IEnumerable в IQueryable.

Cast<TResult>(IEnumerable)

Приведение элементов IEnumerable к указанному типу.

OfType<TResult>(IEnumerable)

Фильтрует элементы IEnumerable на основе указанного типа.

Применяется к