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

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

本逐步解說示範如何使用 XAML 在 WPF 頁面上裝載 Windows Forms System.Windows.Forms.MaskedTextBox 控制項。

如需本逐步解說所示工作的完整程式代碼清單,請參閱 使用 XAML 範例 在 WPF 中裝載 Windows Forms 控制項。

必要條件

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

裝載 Windows Forms 控制項

裝載 MaskedTextBox 控制項

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

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

    • WindowsFormsIntegration

    • System.Windows.Forms

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

  4. 在 元素中 Window ,新增下列命名空間對應。 wf命名空間對應會建立包含 Windows Forms 控制項之元件的參考。

    xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"  
    
  5. 在 元素中 Grid ,新增下列 XAML。

    控制項 MaskedTextBox 會建立為 控制項的 WindowsFormsHost 子系。

    <Grid>
    
        <WindowsFormsHost>
            <wf:MaskedTextBox x:Name="mtbDate" Mask="00/00/0000"/>
        </WindowsFormsHost>
    
    </Grid>
    
    
  6. 按 F5 以建置並執行應用程式。

另請參閱