共用方式為


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

更新:2010 年 8 月

WPF 提供許多具有豐富功能集的控制項。 但是,您有時候可能會想要在 WPF 頁面上使用 Windows Forms 控制項。 例如,您可能對現有的 Windows Forms 控制項做了大筆投資,或擁有具備獨一無二功能的 Windows Forms 控制項。

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

如需這個逐步解說中所說明之工作的完整程式碼清單,請參閱在 WPF 中裝載 Windows Form 控制項範例 (英文)。

必要條件

您需要下列元件才能完成此逐步解說:

  • Visual Studio 2010。

裝載 Windows Form 控制項

若要裝載 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 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
    
    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);
    }
    
  9. 在檔案最上方加入以下 Imports 或 using 陳述式。

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

請參閱

工作

逐步解說:使用 XAML 在 WPF 中裝載 Windows Form 控制項

參考

ElementHost

WindowsFormsHost

概念

逐步解說:在 WPF 中裝載 Windows Form 複合控制項

逐步解說:在 Windows Form 中裝載 WPF 複合控制項

Windows Form 控制項和對等 WPF 控制項

其他資源

WPF 設計工具

在 WPF 中裝載 Windows Form 控制項範例

變更記錄

日期

記錄

原因

2010 年 8 月

更新成 Visual Studio 2010 適用的內容。

客戶回函。