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

更新 : 2010 年 8 月

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

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

  • プロジェクトの作成。

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

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

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

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

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

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

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

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

必須コンポーネント

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

  • Visual Studio 2010.

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

プロジェクトの作成

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

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

  2. ソリューション エクスプローラーで、次のアセンブリへの参照を追加します。

    • WindowsFormsIntegration

    • System.Windows.Forms

  3. WPF デザイナーで MainWindow.xaml を開きます。

  4. Window 要素に、次の Windows Forms名前空間の割り当てを追加します。

    xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
    
  5. Name プロパティを割り当てて、既定の Grid 要素に mainGrid という名前を付けます。

        <Grid x:Name="mainGrid">
    

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

顧客のマスター一覧が ListBox コントロールに表示されます。 ListBox コントロールのビジュアル ツリーを制御する ListItemsTemplate という名前の DataTemplate オブジェクトを定義するコード例を次に示します。 この 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>
    

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

選択した顧客に対応する注文が、dataGridView1 という名前の System.Windows.Forms.DataGridView コントロールに表示されます。 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 を使用すると、データ ソースをプロジェクトに簡単に追加できます。 この手順では、厳密に型指定されたデータ セットをプロジェクトに追加します。 選択されたテーブルごとのテーブル アダプターなどの他のサポート クラスもいくつか追加されます。

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

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

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

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

  4. データベース オブジェクトの選択を求められた場合は、Customers テーブルと Orders テーブルを選択し、生成されたデータセットに NorthwindDataSet という名前を付けます。

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

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

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

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

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

    このコードでは、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. コンストラクターに次のコードをコピーします。

    このコードでは、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 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;
    }
    
  4. MainWindow.xaml を開きます。

  5. デザイン ビューまたは XAML ビューで、Window 要素を選択します。

  6. [プロパティ] ウィンドウの [イベント] タブをクリックします。

  7. Loaded イベントをダブルクリックします。

  8. Loaded イベント ハンドラーに次のコードをコピーします。

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

    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
    
    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);
    }
    
  9. 次のコードを MainWindow クラス定義にコピーします。

    このメソッドは 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;
    }
    
  10. F5 キーを押してアプリケーションをビルドし、実行します。

参照

参照

ElementHost

WindowsFormsHost

概念

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

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

その他の技術情報

WPF デザイナー

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

履歴の変更

日付

履歴

理由

2010 年 8 月

Visual Studio 2010 用に更新。

カスタマー フィードバック