データ ソースをコントロールにバインドすることは、Windows フォームと WPF のどちらを使用しているかに関係なく、基になるデータへのアクセス権をユーザーに提供するために不可欠です。 このチュートリアルでは、Windows フォームと WPF コントロールの両方を含むハイブリッド アプリケーションでデータ バインディングを使用する方法について説明します。
このチュートリアルで説明するタスクは次のとおりです。
プロジェクトの作成。
データ テンプレートの定義。
フォーム レイアウトの指定。
データ バインディングの指定。
相互運用を使用したデータの表示。
プロジェクトへのデータ ソースの追加。
データ ソースへのバインド。
このチュートリアルで示すタスクの完全なコード 一覧については、「 ハイブリッド アプリケーションのデータ バインディングのサンプル」を参照してください。
完了すると、ハイブリッド アプリケーションのデータ バインディング機能について理解できるようになります。
[前提条件]
このチュートリアルを完了するには、次のコンポーネントが必要です。
Visual Studio。
Microsoft SQL Server で実行されている Northwind サンプル データベースへのアクセス。
プロジェクトの作成
プロジェクトを作成して設定するには
WPFWithWFAndDatabinding
という名前の WPF アプリケーション プロジェクトを作成します。ソリューション エクスプローラーで、次のアセンブリへの参照を追加します。
WindowsFormsIntegration
System.Windows.Forms
WPF デザイナーで MainWindow.xaml を開きます。
Window要素に、次の Windows フォーム名前空間マッピングを追加します。
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>
フォーム レイアウトの指定
フォームのレイアウトは、3 つの行と 3 つの列を持つグリッドによって定義されます。 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>
ラベル コントロールを設定するには
次の 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 フォーム コントロールの親です。
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 キーを押して、アプリケーションをビルドして実行します。
こちらも参照ください
.NET Desktop feedback