BindingContext 类

管理从 Control 类继承的任意对象的 BindingManagerBase 对象集合。

**命名空间:**System.Windows.Forms
**程序集:**System.Windows.Forms(在 system.windows.forms.dll 中)

语法

声明
Public Class BindingContext
    Implements ICollection, IEnumerable
用法
Dim instance As BindingContext
public class BindingContext : ICollection, IEnumerable
public ref class BindingContext : ICollection, IEnumerable
public class BindingContext implements ICollection, IEnumerable
public class BindingContext implements ICollection, IEnumerable

备注

每个 Windows 窗体至少有一个 BindingContext 对象,此对象管理该窗体的 BindingManagerBase 对象。由于 BindingManagerBase 类是抽象类,因此 Item 属性的返回类型是 CurrencyManagerPropertyManager。如果数据源是只能返回单个属性(而不是对象列表)的对象,则 TypePropertyManager。例如,如果指定 TextBox 作为数据源,则返回 PropertyManager。另一方面,如果数据源是实现 IListIBindingList 的对象,则返回 CurrencyManager

对于 Windows 窗体上的每个数据源,都有单个 CurrencyManagerPropertyManager。由于可能有多个数据源与 Windows 窗体关联,使用 BindingContext 可以检索与数据源关联的任何特定的 CurrencyManager

提示

当使用 Item 属性时,BindingContext 将创建一个新的 BindingManagerBase(如果尚不存在)。这可能会引起混淆,因为返回的对象可能并未管理所需的列表(或任何列表)。若要防止返回无效的 BindingManagerBase,请使用 Contains 方法确定所需的 BindingManagerBase 是否已存在。

如果使用容器控件(如 GroupBoxPanelTabControl)来包含数据绑定控件,则可以仅为该容器控件及其控件创建一个 BindingContext。然后,窗体的每一部分都可以由它自己的 BindingManagerBase 来管理。有关为同一数据源创建多个 BindingManagerBase 对象的更多信息,请参见 BindingContext 构造函数。

如果将 TextBox 控件添加到某个窗体并将其绑定到数据集中的表列,则该控件与此窗体的 BindingContext 进行通信。BindingContext 反过来与此数据关联的特定 CurrencyManager 进行通信。如果您查询了 CurrencyManagerPosition 属性,它会报告此 TextBox 控件的当前绑定记录。在下面的代码示例中,通过 TextBox 控件所在的窗体的 BindingContext,将此控件绑定到 dataSet1 数据集中 Customers 表的 FirstName 列。

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

您可以将第二个 TextBox 控件 (TextBox2) 添加到窗体上并将其绑定到同一数据集中的 Customers 表的 LastName 列。BindingContext 可以识别第一个绑定(TextBox1Customers.FirstName 的绑定),因此它将使用同一个 CurrencyManager,原因是两个文本框都绑定到同一个数据集 (DataSet1)。

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

如果您将 TextBox2 绑定到另一个不同的数据集,则 BindingContext 创建并管理第二个 CurrencyManager

以一致的方式设置 DataSourceDisplayMember 属性很重要;如果不一致,BindingContext 会为同一个数据集创建多个货币管理器,而这将导致错误。下面的代码示例显示几种设置属性及其关联的 BindingContext 对象的方法。只要在整个代码中保持一致,就可以使用以下任意一种方法来设置属性。

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;

提示

大多数 Windows 窗体应用程序都通过 BindingSource 绑定。BindingSource 组件封装 CurrencyManager 并公开 CurrencyManager 编程接口。当使用 BindingSource 进行绑定时,应使用由 BindingSource 公开的成员来操作“货币”(即 Position),而不是遍历 BindingContext

示例

下面的代码示例创建四个 Binding 对象,以将五个控件(一个 DateTimePicker 控件和四个 TextBox 控件)绑定到几个数据源。然后使用 BindingContext 为每个数据源获取 BindingManagerBase

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
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");
}
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.get_DataBindings().Add(new Binding("Text", ds, 
        "customers.custName"));
    text2.get_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.get_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.add_Parse(new ConvertEventHandler(CurrencyStringToDecimal));
    b.add_Format(new ConvertEventHandler(DecimalToCurrencyString));
    text3.get_DataBindings().Add(b);

    // Get the BindingManagerBase for the Customers table. 
    bmCustomers = this.get_BindingContext().get_Item(ds, "Customers");

    /* Get the BindingManagerBase for the Orders table using the 
       RelationName. 
     */
    bmOrders = this.get_BindingContext().get_Item(ds, 
        "customers.CustToOrders");

    /* Bind the fourth TextBox control's Text property to the
       third control's Text property. 
     */
    text4.get_DataBindings().Add("Text", text3, "Text");
} //BindControls
  protected function 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. */
     var b : Binding = new Binding
        ("Text", ds, "customers.custToOrders.OrderAmount");
     b.add_Parse(CurrencyStringToDecimal);
     b.add_Format(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"];
  }

  private function DecimalToCurrencyString(sender, cevent : 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". */

     // We can only convert to string type. 
     if(cevent.DesiredType != String.GetType()) return;

     cevent.Value = (Decimal(cevent.Value)).ToString("c");
  }

  private function CurrencyStringToDecimal(sender, cevent : ConvertEventArgs)
  {   
     /* This method is the Parse event-handler. The Parse event 
        occurs whenever the displayed value changes. The static 
        ToDecimal method of the Convert class converts the 
        value back to its native Decimal type. */

     // Can only convert to Decimal type.
     if(cevent.DesiredType != Decimal.GetType()) return;

     cevent.Value = Decimal.Parse(cevent.Value.ToString(),
         NumberStyles.Currency, null);

     /* To see that no precision is lost, print the unformatted 
        value. For example, changing a value to "10.0001" 
        causes the control to display "10.00", but the 
        unformatted value remains "10.0001". */
     Console.WriteLine(cevent.Value);
  }

  protected function button1_Click(sender, e : System.EventArgs)
  {
     // Go to the previous item in the Customer list.
     bmCustomers.Position -= 1;
  }

  protected function button2_Click(sender, e : System.EventArgs)
  {
     // Go to the next item in the Customer list.
     bmCustomers.Position += 1;
  }
   
  protected function button3_Click(sender, e : System.EventArgs)
  {
     // Go to the previous item in the Orders list.
     bmOrders.Position-=1;
  }

  protected function button4_Click(sender, e : System.EventArgs)
  {
     // Go to the next item in the Orders list.
     bmOrders.Position+=1;
  }

  // Create a DataSet with two tables and populate it.
  private function MakeDataSet()
  {
     // Create a DataSet.
     ds = new DataSet("myDataSet");
     
     // Create two DataTables.
     var tCust : DataTable = new DataTable("Customers");
     var tOrders : DataTable= new DataTable("Orders");

     // Create two columns, and add them to the first table.
     var cCustID : DataColumn = new DataColumn("CustID", Int32);
     var cCustName : DataColumn = new DataColumn("CustName");
     tCust.Columns.Add(cCustID);
     tCust.Columns.Add(cCustName);

     // Create three columns, and add them to the second table.
     var cID : DataColumn  = 
        new DataColumn("CustID", Int32);
     var cOrderDate : DataColumn  = 
        new DataColumn("orderDate", DateTime);
     var cOrderAmount : DataColumn = 
        new DataColumn("OrderAmount", Decimal);
     tOrders.Columns.Add(cOrderAmount);
     tOrders.Columns.Add(cID);
     tOrders.Columns.Add(cOrderDate);

     // Add the tables to the DataSet.
     ds.Tables.Add(tCust);
     ds.Tables.Add(tOrders);

     // Create a DataRelation, and add it to the DataSet.
     var dr : DataRelation = new DataRelation
     ("custToOrders", cCustID , cID);
     ds.Relations.Add(dr);
  
     /* Populate the tables. For each customer and order, 
        create need two DataRow variables. */
     var newRow1 : DataRow;
     var newRow2 : DataRow;

     // Create three customers in the Customers Table.
     for(var i : int = 1; i < 4; i++)
     {
        newRow1 = tCust.NewRow();
        newRow1["custID"] = i;
        // Add the row to the Customers table.
        tCust.Rows.Add(newRow1);
     }
     // Give each customer a distinct name.
     tCust.Rows[0]["custName"] = "Alpha";
     tCust.Rows[1]["custName"] = "Beta";
     tCust.Rows[2]["custName"] = "Omega";
     
     // For each customer, create five rows in the Orders table.
     for(var j : int = 1; j < 4; j++)
     {
        for(var k : int = 1; k < 6; k++)
        {
           newRow2 = tOrders.NewRow();
           newRow2["CustID"]= j;
           newRow2["orderDate"]= new DateTime(2001, j, k * 2);
           newRow2["OrderAmount"] = j * 10 + k  * .1;
           // Add the row to the Orders table.
           tOrders.Rows.Add(newRow2);
        }
     }
  }
}

继承层次结构

System.Object
  System.Windows.Forms.BindingContext

线程安全

此类型的任何公共静态(Visual Basic 中的 Shared)成员都是线程安全的,但不保证所有实例成员都是线程安全的。

平台

Windows 98、Windows 2000 SP4、Windows CE、Windows Millennium Edition、Windows Mobile for Pocket PC、Windows Mobile for Smartphone、Windows Server 2003、Windows XP Media Center Edition、Windows XP Professional x64 Edition、Windows XP SP2、Windows XP Starter Edition

.NET Framework 并不是对每个平台的所有版本都提供支持。有关受支持版本的列表,请参见系统要求

版本信息

.NET Framework

受以下版本支持:2.0、1.1、1.0

.NET Compact Framework

受以下版本支持:2.0、1.0

请参见

参考

BindingContext 成员
System.Windows.Forms 命名空间
BindingManagerBase
Binding 类
BindingsCollection