演练:在 WPF 中承载 Windows 窗体控件

WPF 提供了许多具有丰富功能集的控件。 但是,你有时可能希望在 WPF 页上使用 Windows 窗体控件。 例如,你可能已经为现有的 Windows 窗体控件花费了大量金钱,或者你的 Windows 窗体控件只能提供特殊的功能。

本演练演示如何使用代码在 WPF 页上承载 Windows 窗体 System.Windows.Forms.MaskedTextBox 控件。

有关本演练中介绍的任务的完整代码列表,请参阅在 WPF 示例中承载 Windows 窗体控件

先决条件

若要完成本演练,必须具有 Visual Studio。

承载 Windows 窗体控件

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

另请参阅