Bagikan melalui


Panduan: Menghosting Kontrol Formulir Windows di WPF

WPF menyediakan banyak kontrol dengan set fitur yang kaya. Namun, Terkadang Anda mungkin ingin menggunakan kontrol Formulir Windows di halaman WPF Anda. Misalnya, Anda mungkin memiliki investasi besar dalam kontrol Formulir Windows yang ada, atau Anda mungkin memiliki kontrol Formulir Windows yang menyediakan fungsionalitas unik.

Panduan ini menunjukkan kepada Anda cara menghosting kontrol Formulir Windows System.Windows.Forms.MaskedTextBox di halaman WPF dengan menggunakan kode.

Untuk daftar kode lengkap tugas yang diperlihatkan dalam panduan ini, lihat Menghosting Kontrol Formulir Windows dalam Sampel WPF.

Prasyarat

Anda memerlukan Visual Studio untuk menyelesaikan panduan ini.

Menghosting Kontrol Formulir Windows

Untuk menghosting kontrol MaskedTextBox

  1. Buat proyek Aplikasi WPF bernama HostingWfInWpf.

  2. Tambahkan referensi ke rakitan berikut.

    • WindowsFormsIntegration

    • System.Windows.Forms

  3. Buka MainWindow.xaml di WPF Designer.

  4. Beri nama Grid elemen grid1.

    <Grid Name="grid1">
        
    </Grid>
    
  5. Dalam tampilan Desain atau tampilan XAML, pilih Window elemen .

  6. Di jendela Properti, klik tab Peristiwa .

  7. Loaded Klik dua kali peristiwa.

  8. Sisipkan kode berikut untuk menangani Loaded peristiwa.

    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. Di bagian atas file, tambahkan pernyataan atau using berikut.Imports

    using System.Windows.Forms;
    
    Imports System.Windows.Forms
    
  10. Tekan F5 untuk membangun dan menjalankan aplikasi.

Baca juga