Поделиться через


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
Наследование
Производный

Примеры

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

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)

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

OnCollectionChanging(CollectionChangeEventArgs)

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

Remove(Binding)

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

RemoveAt(Int32)

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

RemoveCore(Binding)

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

ShouldSerializeMyAll()

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

ToString()

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

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

События

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

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

CollectionChanging

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

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

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

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

AsQueryable(IEnumerable)

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

Cast<TResult>(IEnumerable)

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

OfType<TResult>(IEnumerable)

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

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

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