逐步解說:使用 XAML 將 Windows Forms 控制項裝載在 WPF 中Walkthrough: Hosting a Windows Forms Control in WPF by Using XAML

WPFWPF 提供具有豐富功能集的許多控制項。provides many controls with a rich feature set. 不過,您有時可以使用Windows FormsWindows Forms控制上您WPFWPF頁面。However, you may sometimes want to use Windows FormsWindows Forms controls on your WPFWPF pages. 比方說,您可能已長期開發現有Windows FormsWindows Forms控制項,或您可能會有Windows FormsWindows Forms控制項,提供獨特的功能。For example, you may have a substantial investment in existing Windows FormsWindows Forms controls, or you may have a Windows FormsWindows Forms control that provides unique functionality.

本逐步解說會示範如何裝載 Windows FormsSystem.Windows.Forms.MaskedTextBox控制WPFWPF頁面上,使用XAMLXAMLThis walkthrough shows you how to host a Windows Forms System.Windows.Forms.MaskedTextBox control on a WPFWPF page by using XAMLXAML.

如需完整的程式碼的清單在本逐步解說所示範的工作,請參閱 < 裝載 Windows Forms 控制項中所使用的 XAML 範例 WPFFor a complete code listing of the tasks shown in this walkthrough, see Hosting a Windows Forms Control in WPF by Using XAML Sample.

必要條件Prerequisites

若要完成這個逐步解說,您必須具有 Visual Studio。You need Visual Studio to complete this walkthrough.

裝載 Windows Forms 控制項Hosting the Windows Forms Control

裝載 MaskedTextBox 控制項To host the MaskedTextBox control

  1. 建立 WPF 應用程式專案,名為HostingWfInWpfWithXamlCreate a WPF Application project named HostingWfInWpfWithXaml.

  2. 加入下列組件的參考。Add references to the following assemblies.

    • WindowsFormsIntegrationWindowsFormsIntegration

    • System.Windows.FormsSystem.Windows.Forms

  3. 開啟 MainWindow.xaml 中的WPF 設計工具WPF DesignerOpen MainWindow.xaml in the WPF 設計工具WPF Designer.

  4. Window項目,加入下列命名空間對應。In the Window element, add the following namespace mapping. wf命名空間對應會建立包含在 Windows Form 控制項的組件的參考。The wf namespace mapping establishes a reference to the assembly that contains the Windows Forms control.

    xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"  
    
  5. Grid加入下列 XAML 項目。In the Grid element add the following XAML.

    MaskedTextBox控制項會建立為子系WindowsFormsHost控制項。The MaskedTextBox control is created as a child of the WindowsFormsHost control.

    <Grid>
    
        <WindowsFormsHost>
            <wf:MaskedTextBox x:Name="mtbDate" Mask="00/00/0000"/>
        </WindowsFormsHost>
    
    </Grid>
    
    
  6. 按 F5 鍵建置並執行應用程式。Press F5 to build and run the application.

另請參閱See also