Share via


HOW TO:繫結至 ADO.NET 資料來源

這個範例顯示如何將 Windows Presentation Foundation (WPF) ListBox 控制項繫結至 ADO.NET DataSet。

範例

在這個範例中,OleDbConnection 物件會用於連接到資料來源,這個資料來源是連接字串 (Connection String) 中指定的 Access MDB 檔案。 建立連接之後,會建立 OleDbDataAdpater 物件。 OleDbDataAdpater 物件會執行一個 select Structured Query Language (SQL) 陳述式從資料庫擷取資料錄集 (Recordset)。 SQL 命令的結果會透過呼叫 OleDbDataAdapter 的 Fill 方法,儲存在 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

概念

資料繫結概觀

其他資源

資料繫結 HOW TO 主題