将winform控件插入WPF

时间:2013-09-09 20:56:49

标签: c# wpf winforms

我们有一个在Windows窗体中创建的旧库。我们想在现有的WPF应用程序中使用此库。根据{{​​3}},这是可能的。有没有人试过这样做?我们需要注意哪些警告?有什么建议吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

有很多关于这个问题的资料来源。以下是一些来自简单Google搜索的

我将解释第一个链接,因为它相当简单易用。实际上没有太多代码。

首先,您需要添加对以下程序集的引用:

  • WindowsFormsIntegration程序
  • System.Windows.Forms的

然后创建一个网格(在本例中名为Grid1)。

以下是代码隐藏:

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);
}

您所做的只是实例化WindowsFormsHost,然后添加名为mtbDate的子控件。实例化您自己的控件并使用相同的方法添加它。然后像在Win Forms中一样操纵它。

然后在课程顶部添加一个使用:

using System.Windows.Forms;

我希望有所帮助。