不論您是使用 Windows Forms 還是 WPF,將數據源系結至控件對於為使用者提供基礎數據的存取權至關重要。 本逐步解說說明如何在包含 Windows Forms 和 WPF 控件的混合式應用程式中使用數據系結。
這個逐步解說中所述的工作包括:
建立專案。
定義資料範本。
指定表單版面配置。
指定資料繫結。
使用交互操作來顯示資料。
將資料來源新增至專案。
繫結至資料來源。
如需本逐步解說中所述工作的完整程式碼清單,請參閱 Data Binding in Hybrid Applications Sample (混合應用程式範例中的資料繫結)。
完成後,您就會了解混合應用程式中的資料繫結功能。
必要條件
您需要下列元件才能完成這個逐步解說:
Visual Studio。
在 Microsoft SQL Server 上執行的 Northwind 範例資料庫存取權。
建立專案
建立並設定專案
建立名為
WPFWithWFAndDatabinding
的 WPF 應用程式專案。在 [方案總管] 中,加入下列組件的參考。
WindowsFormsIntegration
System.Windows.Forms
在 WPF 設計工具中開啟 MainWindow.xaml。
在 元素中 Window ,新增下列 Windows Forms 命名空間對應。
xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
藉由指派 屬性來Grid命名預設
mainGrid
專案Name。<Grid x:Name="mainGrid">
定義資料範本
客戶的主要清單會顯示在控制件中 ListBox 。 下列程式代碼範例會 DataTemplate 定義名為 ListItemsTemplate
的物件,以控制控件的可視化樹狀 ListBox 結構。 這會 DataTemplate 指派給 ListBox 控件的 ItemTemplate 屬性。
定義資料範本
將下列 XAML Grid 複製到專案的宣告中。
<Grid.Resources> <DataTemplate x:Key="ListItemsTemplate"> <TextBlock Text="{Binding Path=ContactName}"/> </DataTemplate> </Grid.Resources>
指定表單版面配置
表單的版面配置定義具有三個資料列和三個資料行的格線。 Label 會提供控件來識別 Customers 數據表中的每個數據行。
設定格線版面配置
將下列 XAML Grid 複製到專案的宣告中。
<Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="Auto"/> </Grid.ColumnDefinitions>
設定 Label 控制項
將下列 XAML Grid 複製到專案的宣告中。
<StackPanel Orientation="Vertical" Grid.Row="0" Grid.Column="1"> <Label Margin="20,38,5,2">First Name:</Label> <Label Margin="20,0,5,2">Company Name:</Label> <Label Margin="20,0,5,2">Phone:</Label> <Label Margin="20,0,5,2">Address:</Label> <Label Margin="20,0,5,2">City:</Label> <Label Margin="20,0,5,2">Region:</Label> <Label Margin="20,0,5,2">Postal Code:</Label> </StackPanel>
指定資料繫結
客戶的主要清單會顯示在控制件中 ListBox 。 附加 ListItemsTemplate
的 會將控件系結 TextBlock 至資料庫中的 ContactName
欄位。
每個客戶記錄的詳細數據會顯示在數個 TextBox 控制件中。
指定資料繫結
將下列 XAML Grid 複製到專案的宣告中。
類別 Binding 會將 TextBox 控件系結至資料庫中的適當欄位。
<StackPanel Orientation="Vertical" Grid.Row="0" Grid.Column="0"> <Label Margin="20,5,5,0">List of Customers:</Label> <ListBox x:Name="listBox1" Height="200" Width="200" HorizontalAlignment="Left" ItemTemplate="{StaticResource ListItemsTemplate}" IsSynchronizedWithCurrentItem="True" Margin="20,5,5,5"/> </StackPanel> <StackPanel Orientation="Vertical" Grid.Row="0" Grid.Column="2"> <TextBox Margin="5,38,5,2" Width="200" Text="{Binding Path=ContactName}"/> <TextBox Margin="5,0,5,2" Width="200" Text="{Binding Path=CompanyName}"/> <TextBox Margin="5,0,5,2" Width="200" Text="{Binding Path=Phone}"/> <TextBox Margin="5,0,5,2" Width="200" Text="{Binding Path=Address}"/> <TextBox Margin="5,0,5,2" Width="200" Text="{Binding Path=City}"/> <TextBox Margin="5,0,5,2" Width="30" HorizontalAlignment="Left" Text="{Binding Path=Region}"/> <TextBox Margin="5,0,5,2" Width="50" HorizontalAlignment="Left" Text="{Binding Path=PostalCode}"/> </StackPanel>
使用交互操作來顯示資料
對應至所選客戶的訂單會顯示在名為 System.Windows.Forms.DataGridView的dataGridView1
控制件中。 控件 dataGridView1
會系結至程序代碼後置檔案中的數據源。
WindowsFormsHost控件是這個 Windows Forms 控件的父系。
在 DataGridView 控制項中顯示資料
將下列 XAML Grid 複製到專案的宣告中。
<WindowsFormsHost Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="3" Margin="20,5,5,5" Height="300"> <wf:DataGridView x:Name="dataGridView1"/> </WindowsFormsHost>
將資料來源新增至專案
使用 Visual Studio,您可以輕鬆地將數據源新增至專案。 此程序會將強型別的資料集新增至專案。 也會新增數個其他支援類別,例如每個所選擇資料表的資料表配置器。
若要新增資料來源
從 [ 數據] 功能表中,選取 [新增數據源]。
在 [資料來源組態精靈] 中,使用資料集建立與 Northwind 資料庫的連線。 如需詳細資訊,請參閱如何:連接至資料庫中的資料。
[資料來源組態精靈] 提示您時,請將連線字串儲存為
NorthwindConnectionString
。重要
在連接字串內儲存機密資訊 (例如密碼) 會影響應用程式的安全性。 使用 Windows 驗證 (也稱為整合式安全性) 是控制資料庫存取的更安全方式。 如需詳細資訊,請參閱保護連線資訊。
當系統提示您選擇資料庫物件時,請選擇
Customers
資料Orders
表,並將產生的數據集NorthwindDataSet
命名為 。
繫結至資料來源
元件 System.Windows.Forms.BindingSource 會為應用程式的數據源提供統一介面。 繫結至資料來源是在程式碼後置檔案中進行實作。
繫結至資料來源
開啟程式碼後置檔案,命名為 MainWindow.xaml.vb 或 MainWindow.xaml.cs。
將下列程式代碼複製到
MainWindow
類別定義中。此程式代碼會 BindingSource 宣告連接到資料庫的元件和相關聯的協助程序類別。
private System.Windows.Forms.BindingSource nwBindingSource; private NorthwindDataSet nwDataSet; private NorthwindDataSetTableAdapters.CustomersTableAdapter customersTableAdapter = new NorthwindDataSetTableAdapters.CustomersTableAdapter(); private NorthwindDataSetTableAdapters.OrdersTableAdapter ordersTableAdapter = new NorthwindDataSetTableAdapters.OrdersTableAdapter();
Private nwBindingSource As System.Windows.Forms.BindingSource Private nwDataSet As NorthwindDataSet Private customersTableAdapter As New NorthwindDataSetTableAdapters.CustomersTableAdapter() Private ordersTableAdapter As New NorthwindDataSetTableAdapters.OrdersTableAdapter()
將下列程式碼複製至建構函式。
此程式代碼會建立並初始化 BindingSource 元件。
public MainWindow() { InitializeComponent(); // Create a DataSet for the Customers data. this.nwDataSet = new NorthwindDataSet(); this.nwDataSet.DataSetName = "nwDataSet"; // Create a BindingSource for the Customers data. this.nwBindingSource = new System.Windows.Forms.BindingSource(); this.nwBindingSource.DataMember = "Customers"; this.nwBindingSource.DataSource = this.nwDataSet; }
Public Sub New() InitializeComponent() ' Create a DataSet for the Customers data. Me.nwDataSet = New NorthwindDataSet() Me.nwDataSet.DataSetName = "nwDataSet" ' Create a BindingSource for the Customers data. Me.nwBindingSource = New System.Windows.Forms.BindingSource() Me.nwBindingSource.DataMember = "Customers" Me.nwBindingSource.DataSource = Me.nwDataSet End Sub
開啟 MainWindow.xaml。
在 [設計視圖] 或 [XAML 檢視] 中,選取 Window 元素。
在 [屬性] 視窗中,按一下 [事件] 索引標籤。
連按兩下 Loaded 事件。
將下列程式代碼複製到 Loaded 事件處理程式。
此程式代碼會將 BindingSource 元件指派為數據內容,並填入
Customers
和Orders
配接器物件。private void Window_Loaded(object sender, RoutedEventArgs e) { // Fill the Customers table adapter with data. this.customersTableAdapter.ClearBeforeFill = true; this.customersTableAdapter.Fill(this.nwDataSet.Customers); // Fill the Orders table adapter with data. this.ordersTableAdapter.Fill(this.nwDataSet.Orders); // Assign the BindingSource to // the data context of the main grid. this.mainGrid.DataContext = this.nwBindingSource; // Assign the BindingSource to // the data source of the list box. this.listBox1.ItemsSource = this.nwBindingSource; // Because this is a master/details form, the DataGridView // requires the foreign key relating the tables. this.dataGridView1.DataSource = this.nwBindingSource; this.dataGridView1.DataMember = "FK_Orders_Customers"; // Handle the currency management aspect of the data models. // Attach an event handler to detect when the current item // changes via the WPF ListBox. This event handler synchronizes // the list collection with the BindingSource. // BindingListCollectionView cv = CollectionViewSource.GetDefaultView( this.nwBindingSource) as BindingListCollectionView; cv.CurrentChanged += new EventHandler(WPF_CurrentChanged); }
Private Sub Window_Loaded( _ ByVal sender As Object, _ ByVal e As RoutedEventArgs) ' Fill the Customers table adapter with data. Me.customersTableAdapter.ClearBeforeFill = True Me.customersTableAdapter.Fill(Me.nwDataSet.Customers) ' Fill the Orders table adapter with data. Me.ordersTableAdapter.Fill(Me.nwDataSet.Orders) ' Assign the BindingSource to ' the data context of the main grid. Me.mainGrid.DataContext = Me.nwBindingSource ' Assign the BindingSource to ' the data source of the list box. Me.listBox1.ItemsSource = Me.nwBindingSource ' Because this is a master/details form, the DataGridView ' requires the foreign key relating the tables. Me.dataGridView1.DataSource = Me.nwBindingSource Me.dataGridView1.DataMember = "FK_Orders_Customers" ' Handle the currency management aspect of the data models. ' Attach an event handler to detect when the current item ' changes via the WPF ListBox. This event handler synchronizes ' the list collection with the BindingSource. ' Dim cv As BindingListCollectionView = _ CollectionViewSource.GetDefaultView(Me.nwBindingSource) AddHandler cv.CurrentChanged, AddressOf WPF_CurrentChanged End Sub
將下列程式代碼複製到
MainWindow
類別定義中。這個方法會處理 事件, CurrentChanged 並更新數據系結的目前專案。
// This event handler updates the current item // of the data binding. void WPF_CurrentChanged(object sender, EventArgs e) { BindingListCollectionView cv = sender as BindingListCollectionView; this.nwBindingSource.Position = cv.CurrentPosition; }
' This event handler updates the current item ' of the data binding. Private Sub WPF_CurrentChanged(ByVal sender As Object, ByVal e As EventArgs) Dim cv As BindingListCollectionView = sender Me.nwBindingSource.Position = cv.CurrentPosition End Sub
按 F5 以建置並執行應用程式。