チュートリアル : ハイブリッド アプリケーションでのデータへのバインディング

更新 : 2007 年 11 月

データ ソースのコントロールへのバインディングは、Windows フォームと WPF のどちらを使用しているかに関係なく、ユーザーが基になるデータにアクセスできるようにするために不可欠です。このチュートリアルでは、Windows フォーム コントロールと WPF コントロールの両方を含むハイブリッド アプリケーションでデータ バインディングを使用する方法を示します。

このチュートリアルでは、以下のタスクを行います。

  • プロジェクトの作成。

  • データ テンプレートの定義。

  • フォーム レイアウトの指定。

  • データ バインディングの指定。

  • 相互運用を使用したデータの表示。

  • プロジェクトへのデータ ソースの追加。

  • データ ソースへのバインディング。

このチュートリアルで示すタスクの完全なコード一覧については、「ハイブリッド アプリケーションでのデータ バインディングのサンプル」を参照してください。

終了すると、ハイブリッド アプリケーションのデータ バインディング機能を理解できるようになります。

メモ :

使用している設定またはエディションによっては、ヘルプの記載と異なるダイアログ ボックスやメニュー コマンドが表示される場合があります。設定を変更するには、[ツール] メニューの [設定のインポートとエクスポート] をクリックします。詳細については、「Visual Studio の設定」を参照してください。

前提条件

このチュートリアルを完了するには、次のコンポーネントが必要です。

  • Visual Studio 2008.

  • Microsoft SQL Server で実行されている Northwind サンプル データベースへのアクセス。

プロジェクトの作成

プロジェクトを作成し、設定するには

  1. WPFWithWFAndDatabinding という名前の WPF アプリケーション プロジェクトを作成します。

  2. ソリューション エクスプローラで、WindowsFormsIntegration.dll という名前の WindowsFormsIntegration アセンブリへの参照を追加します。

  3. ソリューション エクスプローラで、System.Windows.Forms.dll という名前の Windows フォーム アセンブリへの参照を追加します。

  4. WPF デザイナで Window1.xaml を開きます。

  5. ファイルの先頭で、Windows フォーム名前空間を次のコードでマップします。

    <Window x:Class="Window1"
        xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms" 
        Title="WPFWithWFAndDatabinding"
        Loaded="WindowLoaded"
        >
    
    <Window x:Class="WPFWithWFAndDatabinding.Window1"
        xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms" 
        Title="WPFWithWFAndDatabinding"
        Loaded="WindowLoaded"
        >
    
  6. Name プロパティを割り当てて、既定の Grid 要素に mainGrid という名前を付けます。

    <Grid x:Name="mainGrid">
    
     <Grid x:Name="mainGrid">
    

データ テンプレートの定義

顧客のマスタ一覧が ListBox コントロールに表示されます。ListBox コントロールのビジュアル ツリーを制御する ListItemsTemplate という名前の DataTemplate オブジェクトを定義するコード例を次に示します。この DataTemplate は、ListBox コントロールの ItemTemplate プロパティに割り当てられます。

データ テンプレートを定義するには

  • 次のコードを Grid 要素の宣言にコピーします。

    <Grid.Resources>
      <DataTemplate x:Key="ListItemsTemplate">
        <TextBlock Text="{Binding Path=ContactName}"/>
      </DataTemplate>
    </Grid.Resources>
    
         <Grid.Resources>
                <DataTemplate x:Key="ListItemsTemplate">
                    <TextBlock Text="{Binding Path=ContactName}"/>
                </DataTemplate>
            </Grid.Resources>
    

フォーム レイアウトの指定

フォームのレイアウトは、3 つの行と 3 つの列を持つグリッドで定義されます。Label コントロールで、Customers テーブル内の各列が識別されます。

グリッド レイアウトを設定するには

  • 次のコードを 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>
    
         <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>
    

ラベル コントロールを設定するには

  • 次のコードを 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>
    
         <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 コントロールに表示されます。

データ バインディングを指定するには

  • 次のコードを 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>
    
         <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>
    

相互運用を使用したデータの表示

選択した顧客に対応する注文が、dataGridView1 という名前の System.Windows.Forms.DataGridView コントロールに表示されます。dataGridView1 コントロールは、分離コード ファイルのデータ ソースにバインドされています。WindowsFormsHost コントロールは、この Windows フォーム コントロールの親です。

DataGridView コントロールにデータを表示するには

  • 次のコードを Grid 要素の宣言にコピーします。

    <WindowsFormsHost Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="3" Margin="20,5,5,5" Height="300">
      <wf:DataGridView x:Name="dataGridView1"/>
    </WindowsFormsHost>
    
         <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 を使用すると、データ ソースをプロジェクトに簡単に追加できます。この手順では、厳密に型指定されたデータ セットをプロジェクトに追加します。選択されたテーブルごとのテーブル アダプタなどの他のサポート クラスもいくつか追加されます。

データ ソースを追加するには

  1. [プロジェクト] メニューの [新しいデータ ソースの追加] をクリックします。

  2. データ ソース構成ウィザードで、[新しい接続] をクリックして、Northwind データベースへの接続を作成します。詳細については、「方法 : データベース内のデータに接続する」を参照してください。

  3. データソース構成ウィザードからメッセージが表示されたら、接続文字列を NorthwindConnectionString として保存します。

  4. Customers テーブルと Orders テーブルを選択し、生成されたデータ セットに NorthwindDataSet という名前を付けます。

データ ソースへのバインディング

System.Windows.Forms.BindingSource コンポーネントは、アプリケーションのデータ ソースの統一されたインターフェイスを提供します。データ ソースへのバインディングは、分離コード ファイルで実装されます。

データ ソースにバインドするには

  1. Window1.xaml.cs または Window1.xaml.vb という名前の分離コード ファイルを開きます。

  2. 次のコードを Window1 クラス定義にコピーします。

    このコードでは、BindingSource コンポーネントと、データベースに接続する関連付けられたヘルパ クラスが宣言されます。

    Private nwBindingSource As System.Windows.Forms.BindingSource
    Private nwDataSet As NorthwindDataSet
    Private customersTableAdapter As New NorthwindDataSetTableAdapters.CustomersTableAdapter()
    Private ordersTableAdapter As New NorthwindDataSetTableAdapters.OrdersTableAdapter()
    
    private System.Windows.Forms.BindingSource nwBindingSource;
    private NorthwindDataSet nwDataSet;
    private NorthwindDataSetTableAdapters.CustomersTableAdapter customersTableAdapter = 
        new NorthwindDataSetTableAdapters.CustomersTableAdapter();
    private NorthwindDataSetTableAdapters.OrdersTableAdapter ordersTableAdapter = 
        new NorthwindDataSetTableAdapters.OrdersTableAdapter();
    
  3. InitializeComponent メソッドの呼び出しの直後にある Window1 コンストラクタに次のコードをコピーします。

    このコードでは、BindingSource コンポーネントが作成および初期化されます。

    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
    
    public Window1()
    {
        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;
    }
    
  4. コンストラクタの後にある Window1 クラス定義に次のコードをコピーします。

    このコードでは、Loaded イベント ハンドラが定義されます。このハンドラによって BindingSource コンポーネントがデータ コンテキストとして割り当てられ、Customers および Orders アダプタ オブジェクトが設定されます。

    Private Sub WindowLoaded( _
    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
    
    private void WindowLoaded(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);
    }
    
  5. WindowLoaded メソッドの後にある Window1 クラス定義に次のコードをコピーします。

    このメソッドは CurrentChanged イベントを処理し、データ バインディングの現在の項目を更新します。

    ' 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
    
    // 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;
    }
    
  6. F5 キーを押してアプリケーションをビルドし、実行します。

参照

処理手順

ハイブリッド アプリケーションでのデータ バインディングのサンプル

概念

チュートリアル : Windows Presentation Foundation での Windows フォーム複合コントロールのホスト

チュートリアル : Windows フォームでの Windows Presentation Foundation コントロールのホスト

参照

ElementHost

WindowsFormsHost

その他の技術情報

WPF デザイナ

移行および相互運用性に関する「方法」トピック