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

WPF には、豊富な機能セットを備えた多くのコントロールが用意されています。 ただし、WPF ページで Windows フォーム コントロールを使用する場合があります。 たとえば、既存の Windows フォーム コントロールに多大な投資をしている場合や、独自の機能を提供する Windows フォーム コントロールを使用している場合があります。

このチュートリアルでは、コードを使用して WPF ページで Windows フォーム System.Windows.Forms.MaskedTextBox コントロールをホストする方法について説明します。

このチュートリアルで示されているタスクの完全なコード一覧については、WPF での Windows フォーム コントロールのホストのサンプルを参照してください。

必須コンポーネント

このチュートリアルを完了するには Visual Studio が必要です。

Windows フォーム コントロールのホスト

MaskedTextBox コントロールをホストするには

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

  2. 次のアセンブリへの参照を追加します。

    • WindowsFormsIntegration

    • System.Windows.Forms

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

  4. Grid 要素に grid1 という名前を付けます。

    <Grid Name="grid1">
        
    </Grid>
    
  5. デザイン ビューまたは XAML ビューで、Window 要素を選択します。

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

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

  8. Loaded イベントを処理する次のコードを挿入します。

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        // Create the interop host control.
        System.Windows.Forms.Integration.WindowsFormsHost host =
            new System.Windows.Forms.Integration.WindowsFormsHost();
    
        // Create the MaskedTextBox control.
        MaskedTextBox mtbDate = new MaskedTextBox("00/00/0000");
    
        // Assign the MaskedTextBox control as the host control's child.
        host.Child = mtbDate;
    
        // Add the interop host control to the Grid
        // control's collection of child controls.
        this.grid1.Children.Add(host);
    }
    
    Private Sub Window_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs)
        ' Create the interop host control.
        Dim host As New System.Windows.Forms.Integration.WindowsFormsHost()
    
        ' Create the MaskedTextBox control.
        Dim mtbDate As New MaskedTextBox("00/00/0000")
    
        ' Assign the MaskedTextBox control as the host control's child.
        host.Child = mtbDate
    
        ' Add the interop host control to the Grid
        ' control's collection of child controls.
        Me.grid1.Children.Add(host)
    
    End Sub
    
  9. ファイルの先頭に、次の Imports または using ステートメントを追加します。

    using System.Windows.Forms;
    
    Imports System.Windows.Forms
    
  10. F5 キーを押してアプリケーションをビルドし、実行します。

関連項目