逐步解說:在 WPF 中裝載 Windows Forms 控制項

WPF 提供許多具有豐富功能集的控制項。 不過,您可能有時想要在 WPF 頁面上使用 Windows Forms 控制項。 例如,您可能對現有的 Windows Forms 控制項有大量投資,或者您可能有提供獨特功能的 Windows Forms 控制項。

本逐步解說說明如何使用程式碼在 WPF 頁面上裝載 Windows Forms System.Windows.Forms.MaskedTextBox 控制項。

如需本逐步解說中所顯示工作的完整程式碼清單,請參閱 Hosting a Windows Forms Control in WPF Sample (在 WPF 中裝載 Windows Forms 控制項的範例)。

必要條件

若要完成這個逐步解說,您必須具有 Visual Studio。

裝載 Windows Forms 控制項

裝載 MaskedTextBox 控制項

  1. 建立名為 HostingWfInWpf 的 WPF 應用程式專案。

  2. 加入下列組件的參考。

    • WindowsFormsIntegration

    • System.Windows.Forms

  3. 在 WPF 設計工具中開啟 MainWindow.xaml。

  4. 將專案 grid1 命名為 Grid

    <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. 在檔案頂端,新增下列 Importsusing 語句。

    using System.Windows.Forms;
    
    Imports System.Windows.Forms
    
  10. F5 以建置並執行應用程式。

另請參閱