如何:绑定到 ADO.NET 数据源

本示例演示如何将 Windows Presentation Foundation (WPF) ListBox 控件绑定到 ADO.NET DataSet。

示例

在本示例中,OleDbConnection 对象用于连接到数据源,该数据源是在连接字符串中指定的 Access MDB 文件。 建立连接后,会创建一个 OleDbDataAdpater 对象。 OleDbDataAdpater 对象执行一个 select Structured Query Language (SQL) 语句,以便从数据库中检索记录集。 通过调用 OleDbDataAdapter 的 Fill 方法,此 SQL 命令的结果存储在 DataSet 的 DataTable 中。 本示例中,DataTable 命名为 BookTable。 然后,此示例将 ListBoxDataContext 属性设置为 DataSet 对象。

    Private myDataSet As DataSet

    Private Sub OnInit(ByVal sender As Object, ByVal e As EventArgs)
      Dim mdbFile As String = Path.Combine(AppDataPath, "BookData.mdb")
      Dim connString As String = String.Format("Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}", mdbFile)
      Dim conn As New OleDbConnection(connString)
      Dim adapter As New OleDbDataAdapter("SELECT * FROM BookTable;", conn)

      myDataSet = New DataSet()
      adapter.Fill(myDataSet, "BookTable")

      ' myListBox is a ListBox control.
      ' Set the DataContext of the ListBox to myDataSet
      myListBox.DataContext = myDataSet
    End Sub
DataSet myDataSet;

private void OnInit(object sender, EventArgs e)
{
  string mdbFile = Path.Combine(AppDataPath, "BookData.mdb");
  string connString = string.Format(
      "Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}", mdbFile);
  OleDbConnection conn = new OleDbConnection(connString);
  OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM BookTable;", conn);

  myDataSet = new DataSet();
  adapter.Fill(myDataSet, "BookTable");

  // myListBox is a ListBox control.
  // Set the DataContext of the ListBox to myDataSet
  myListBox.DataContext = myDataSet;
}

然后,我们将 ListBoxItemsSource 属性绑定到 DataSet 的 BookTable:

<ListBox Name="myListBox" Height="200"
  ItemsSource="{Binding Path=BookTable}"
  ItemTemplate  ="{StaticResource BookItemTemplate}"/>

BookItemTemplate 是定义数据显示形式的 DataTemplate

<StackPanel.Resources>
  <c:IntColorConverter x:Key="MyConverter"/>

  <DataTemplate x:Key="BookItemTemplate">
    <Grid>
      <Grid.ColumnDefinitions>
        <ColumnDefinition Width="250" />
        <ColumnDefinition Width="100" />
        <ColumnDefinition Width="*"/>
      </Grid.ColumnDefinitions>
      <TextBlock Text="{Binding Path=Title}" Grid.Column="0"
        FontWeight="Bold" />
      <TextBlock Text="{Binding Path=ISBN}" Grid.Column="1" />
      <TextBlock Grid.Column="2" Text="{Binding Path=NumPages}"
                 Background="{Binding Path=NumPages,
          Converter={StaticResource MyConverter}}"/>
    </Grid>
  </DataTemplate>
</StackPanel.Resources>

IntColorConverter 将 int 转换为颜色。 利用此转换器,如果 NumPages 的值小于 350,则第三个 TextBlockBackground 颜色为绿色,否则为红色。 此处未显示此转换器的实现。

请参见

参考

BindingListCollectionView

概念

数据绑定概述

其他资源

数据绑定帮助主题