操作說明:繫結至 ADO.NET 資料來源

此範例示範如何將 Windows Presentation Foundation (WPF) ListBox 控制項系結至 ADO.NET DataSet

範例

在這個範例中,OleDbConnection 物件會用於連接到資料來源,這個資料來源是連接字串中指定的 Access MDB 檔案。 建立連接之後,會建立 OleDbDataAdapter 物件。 物件 OleDbDataAdapter 會執行 select 結構化查詢語言 (SQL) (SQL) 語句,從資料庫擷取記錄集。 SQL 命令的結果會藉由呼叫 Fill 的 方法儲存在 DataTableDataSetOleDbDataAdapter 中。 這個範例中的 DataTable 名為 BookTable。 然後,此範例會將 DataContextListBox 屬性設定為 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

然後,我們可以將 ItemsSourceListBox 屬性系結至 BookTableDataSet

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

BookItemTemplateDataTemplate是定義資料顯示方式的 :

<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 轉換成色彩。 使用這個轉換子時, Background 如果 的值 NumPages 小於 350 且紅色,則第三 TextBlock 個的色彩會顯示為綠色,否則為紅色。 這裡不顯示轉換器的實作。

另請參閱