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

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

示例

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

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;
}
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

我们可以随后将 ListBoxItemsSource 属性绑定到 DataSetBookTable

<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>

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

另请参阅