Procedura dettagliata: hosting di controlli Windows Form in WPF

WPF offre molti controlli con un set di funzionalità avanzato. Tuttavia, a volte è possibile usare controlli Windows Form nelle pagine WPF. Ad esempio, si potrebbe avere un notevole investimento nei controlli di Windows Form esistenti oppure è possibile avere un controllo Windows Form che fornisce funzionalità uniche.

Questa procedura dettagliata illustra come ospitare un controllo Windows Form System.Windows.Forms.MaskedTextBox in una pagina WPF usando il codice.

Per un listato di codice completo delle attività illustrate in questa procedura dettagliata vedere Esempio di hosting di un controllo Windows Forms in WPF.

Prerequisiti

Per completare la procedura dettagliata, è necessario Visual Studio.

Hosting del controllo Windows Forms

Per ospitare il controllo MaskedTextBox

  1. Creare un progetto di applicazione WPF denominato HostingWfInWpf.

  2. Aggiungere riferimenti agli assembly indicati di seguito.

    • WindowsFormsIntegration

    • System.Windows.Forms

  3. Aprire MainWindow.xaml nella finestra di progettazione WPF.

  4. Denominare l'elemento Gridgrid1.

    <Grid Name="grid1">
        
    </Grid>
    
  5. Nella visualizzazione Progettazione o nella visualizzazione XAML selezionare l'elemento Window .

  6. Nella finestra Proprietà fare clic sulla scheda Eventi.

  7. Fare doppio clic sull'evento Loaded .

  8. Inserire il codice seguente per gestire l'evento 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. Nella parte superiore del file aggiungere l'istruzione o using seguenteImports.

    using System.Windows.Forms;
    
    Imports System.Windows.Forms
    
  10. Premere F5 per compilare ed eseguire l'applicazione.

Vedi anche