次の方法で共有


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

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

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

  • プロジェクトの作成。

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

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

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

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

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

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

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

完了すると、ハイブリッド アプリケーションのデータ バインディング機能について理解できます。

必須コンポーネント

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

  • Visual Studio

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

プロジェクトの作成

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

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

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

    • WindowsFormsIntegration

    • System.Windows.Forms

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

  4. Window 要素に、次の Windows フォーム名前空間マップを追加します。

    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 フォーム コントロールの親です。

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 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()
    
  3. 次のコードをコンストラクターにコピーします。

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

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

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

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

  8. 次のコードを 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
    
  9. 次のコードを 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
    
  10. F5 キーを押してアプリケーションをビルドし、実行します。

関連項目