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 Windows Forms yang ada, atau Anda mungkin memiliki kontrol Windows Forms yang menyediakan fungsionalitas unik.

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

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

Prasyarat

Anda memerlukan Visual Studio untuk menyelesaikan panduan ini.

Menghosting Kontrol Form Windows

Untuk mengelola kontrol MaskedTextBox

  1. Buat proyek Aplikasi WPF bernama HostingWfInWpf.

  2. Tambahkan referensi ke kumpulan rakitan berikut.

    • WindowsFormsIntegration

    • System.Windows.Forms

  3. Buka MainWindow.xaml di WPF Designer.

  4. Beri nama elemen Gridgrid1.

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

  6. Di jendela Properti, klik tab Peristiwa.

  7. Klik dua kali acara Loaded.

  8. Sisipkan kode berikut untuk menangani peristiwa 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. Di bagian atas file, tambahkan pernyataan Imports atau using berikut.

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

Lihat juga