BindingsCollection Класс

Определение

Представляет коллекцию объектов Binding для элемента управления.

public ref class BindingsCollection : System::Windows::Forms::BaseCollection
public class BindingsCollection : System.Windows.Forms.BaseCollection
type BindingsCollection = class
    inherit BaseCollection
Public Class BindingsCollection
Inherits BaseCollection
Наследование
Производный

Примеры

В следующем примере свойство TextBox элемента управления привязывается Text к полю в базе данных.

private:
   void BindTextBoxControl()
   {
      DataSet^ myDataSet = gcnew DataSet;
      /* Insert code to populate the DataSet with tables, 
      columns, and data. */

      // Creates a new Binding object. 
      Binding^ myBinding = gcnew Binding(
         "Text",myDataSet,"customers.custToOrders.OrderAmount" );
      
      // Adds event delegates for the Parse and Format events.
      myBinding->Parse += gcnew ConvertEventHandler( this, &Form1::CurrencyToDecimal );
      myBinding->Format += gcnew ConvertEventHandler( this, &Form1::DecimalToCurrency );
      
      // Adds the new Binding to the BindingsCollection.
      text1->DataBindings->Add( myBinding );
   }

   void DecimalToCurrency( Object^ /*sender*/, ConvertEventArgs^ cevent )
   {
      /* This method is the Format event handler. Whenever the 
      control displays a new value, the value is converted from 
      its native Decimal type to a string. The ToString method 
      then formats the value as a Currency, by using the 
      formatting character "c". */
      cevent->Value = safe_cast<Decimal ^>(cevent->Value)->ToString(  "c" );
   }

   void CurrencyToDecimal( Object^ /*sender*/, ConvertEventArgs^ cevent )
   {
      /* This method is the Parse event handler. The Parse event 
      occurs whenever the displayed value changes. The static 
      Parse method of the Decimal structure converts the 
      string back to its native Decimal type. */
      cevent->Value = Decimal::Parse( cevent->Value->ToString(),
         NumberStyles::Currency, nullptr );
   }
private void BindTextBoxControl()
{
   DataSet myDataSet = new DataSet();
   /* Insert code to populate the DataSet with tables, 
   columns, and data. */

   // Creates a new Binding object. 
   Binding myBinding = new Binding
   ("Text", myDataSet, "customers.custToOrders.OrderAmount");

   // Adds event delegates for the Parse and Format events.
   myBinding.Parse += new ConvertEventHandler(CurrencyToDecimal);
   myBinding.Format += new ConvertEventHandler(DecimalToCurrency);

   // Adds the new Binding to the BindingsCollection.
   text1.DataBindings.Add(myBinding);
}

private void DecimalToCurrency(object sender, 
   ConvertEventArgs cevent)
{
   /* This method is the Format event handler. Whenever the 
   control displays a new value, the value is converted from 
   its native Decimal type to a string. The ToString method 
   then formats the value as a Currency, by using the 
   formatting character "c". */
   cevent.Value = ((decimal) cevent.Value).ToString("c");
}

private void CurrencyToDecimal(object sender, 
   ConvertEventArgs cevent)
{   
   /* This method is the Parse event handler. The Parse event 
   occurs whenever the displayed value changes. The static 
   Parse method of the Decimal structure converts the 
   string back to its native Decimal type. */
   cevent.Value = Decimal.Parse(cevent.Value.ToString(),
   NumberStyles.Currency, null);
}
Private Sub BindTextBoxControl()
   Dim myDataSet As New DataSet()
   ' Insert code to populate the DataSet with tables, columns, and data.

   ' Creates a new Binding object. 
   Dim myBinding As New Binding("Text", myDataSet, _
   "customers.custToOrders.OrderAmount")
   
   ' Adds event delegates for the Parse and Format events.
   AddHandler myBinding.Parse, AddressOf CurrencyToDecimal
   AddHandler myBinding.Format, AddressOf DecimalToCurrency
     
   ' Adds the new Binding to the BindingsCollection.
   text1.DataBindings.Add(myBinding)
End Sub 
    
Private Sub DecimalToCurrency(sender As Object, _
   cevent As ConvertEventArgs)
   ' This method is the Format event handler. Whenever the
   ' control displays a new value, the value is converted from
   ' its native Decimal type to a string. The ToString method
   ' then formats the value as a Currency, by using the
   ' formatting character "c". 
   cevent.Value = CDec(cevent.Value).ToString("c")
End Sub 
    
Private Sub CurrencyToDecimal(sender As Object, _
cevent As ConvertEventArgs)
   ' This method is the Parse event handler. The Parse event
   ' occurs whenever the displayed value changes. The static
   ' Parse method of the Decimal structure converts the 
   ' string back to its native Decimal type. 
   cevent.Value = Decimal.Parse(cevent.Value.ToString(), _
   NumberStyles.Currency, nothing)
   End Sub

Комментарии

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

Свойства

Count

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

IsReadOnly

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

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

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

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

Возвращает объект Binding по указанному индексу.

List

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

SyncRoot

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

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

Методы

Add(Binding)

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

AddCore(Binding)

Добавляет Binding в коллекцию.

Clear()

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

ClearCore()

Удаляет все элементы из коллекции.

CopyTo(Array, Int32)

Копирует все элементы текущего одномерного массива Array в заданный одномерный массив Array, начиная с указанного индекса в массиве назначения 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.

OnCollectionChanging(CollectionChangeEventArgs)

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

Remove(Binding)

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

RemoveAt(Int32)

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

RemoveCore(Binding)

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

ShouldSerializeMyAll()

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

ToString()

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

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

События

CollectionChanged

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

CollectionChanging

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

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

Cast<TResult>(IEnumerable)

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

OfType<TResult>(IEnumerable)

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

AsParallel(IEnumerable)

Позволяет осуществлять параллельный запрос.

AsQueryable(IEnumerable)

Преобразовывает коллекцию IEnumerable в объект IQueryable.

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

См. также раздел