演练:使用 XAML 在 WPF 中托管 Windows 窗体控件

WPF 提供了许多具有丰富功能集的控件。 但是,有时你可能想要在 WPF 页面上使用 Windows 窗体控件。 例如,你可能对现有 Windows 窗体控件进行了大量投资,或者你可能拥有提供独特功能的 Windows 窗体控件。

本演练演示如何使用 XAML 在 WPF 页面上托管 Windows 窗体 System.Windows.Forms.MaskedTextBox 控件。

有关本演练中显示的任务的完整代码列表,请参阅 使用 XAML 示例在 WPF 中托管 Windows 窗体控件

先决条件

需要 Visual Studio 才能完成本演练。

托管 Windows Forms 控件

承载 MaskedTextBox 控件

  1. 创建名为 HostingWfInWpfWithXaml的 WPF 应用程序项目。

  2. 添加对以下程序集的引用。

    • WindowsFormsIntegration

    • System.Windows.Forms

  3. 在 WPF 设计器中打开 MainWindow.xaml。

  4. Window 元素中,添加以下命名空间映射。 命名空间 wf 映射建立对包含 Windows 窗体控件的程序集的引用。

    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 生成并运行应用程序。

另请参阅