在大型 WPF 项目中使用大型 WinForms 项目的一部分
Using part of a large WinForms project inside a large WPF project
这两个应用程序都相当陈旧,并且已经由几个人构建和维护了好几年。目前WinForms项目中使用的其中一个控件确实需要在WPF项目中显示出来
我读过有关在 WPF 项目中使用 WinForms 控件的信息,在大多数情况下,如果您只是实例化一个常规的空 WinForm 控件,它似乎相对简单。
我想知道您如何最好地在另一个项目中使用大型项目的一部分?理想情况下,在发送并加载所需数据后,WinForm 控件将在我们的一个 WPF 控件中的一个选项卡上可见。
这里有一些一般准则。
从您的 WPF 应用程序中,将项目引用添加到:
- 您的 WinForms 项目
WindowsFormsIntegration
System.Windows.Forms
修改您的 XAML 以包含 WindowsFormsHost
:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TabControl>
<TabItem Header="Old Form">
<WindowsFormsHost Name="WinFormsHost"></WindowsFormsHost>
</TabItem>
</TabControl>
</Grid>
</Window>
实例化您的旧 Form
并将其设置为 WindowsFormsHost
的 child。将 TopLevel
设置为 false
否则它会抱怨 "the child control cannot be a top-level form." 也更改 FormBorderStyle
以防止显示表单的标题栏并允许用户拖动表单.
public MainWindow()
{
InitializeComponent();
WinFormsHost.Child =
new Form1 { TopLevel = false, FormBorderStyle = FormBorderStyle.None };
}
你最终得到这样的结果:
您可以在“Walkthrough: Hosting a Windows Forms Control in WPF" and the MSDN documentation for the "WindowsFormsHost Class”中阅读更多内容。
这两个应用程序都相当陈旧,并且已经由几个人构建和维护了好几年。目前WinForms项目中使用的其中一个控件确实需要在WPF项目中显示出来
我读过有关在 WPF 项目中使用 WinForms 控件的信息,在大多数情况下,如果您只是实例化一个常规的空 WinForm 控件,它似乎相对简单。
我想知道您如何最好地在另一个项目中使用大型项目的一部分?理想情况下,在发送并加载所需数据后,WinForm 控件将在我们的一个 WPF 控件中的一个选项卡上可见。
这里有一些一般准则。
从您的 WPF 应用程序中,将项目引用添加到:
- 您的 WinForms 项目
WindowsFormsIntegration
System.Windows.Forms
修改您的 XAML 以包含 WindowsFormsHost
:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TabControl>
<TabItem Header="Old Form">
<WindowsFormsHost Name="WinFormsHost"></WindowsFormsHost>
</TabItem>
</TabControl>
</Grid>
</Window>
实例化您的旧 Form
并将其设置为 WindowsFormsHost
的 child。将 TopLevel
设置为 false
否则它会抱怨 "the child control cannot be a top-level form." 也更改 FormBorderStyle
以防止显示表单的标题栏并允许用户拖动表单.
public MainWindow()
{
InitializeComponent();
WinFormsHost.Child =
new Form1 { TopLevel = false, FormBorderStyle = FormBorderStyle.None };
}
你最终得到这样的结果:
您可以在“Walkthrough: Hosting a Windows Forms Control in WPF" and the MSDN documentation for the "WindowsFormsHost Class”中阅读更多内容。