WPF教程之 WindowsFormsHost控件

杂项控件:

WindowsFormsHost控件

WPF和WinForms是两个不同的UI框架,都是由Microsoft创建的。 WPF是WinForms的一个更现代的替代品,WinForms是第一个.NET UI框架。 为了在两者之间轻松过渡,Microsoft确保WinForms控件仍然可以在WPF应用程序中使用。 这是通过WindowsFormsHost完成的,我们将在本文中讨论。

要通过WindowsFormsHost使用WinForms中的控件,需要在应用程序中添加对以下程序集的引用:

  • WindowsFormsIntegration
  • System.Windows.Forms

在Visual Studio中,通过右键单击项目中的“引用”节点并选择“添加引用”来完成此操作:

WPF教程之 WindowsFormsHost控件

在弹出的对话框中,选择“程序集”,然后勾选我们需要添加的两个程序集:


WPF教程之 WindowsFormsHost控件

使用WinForms WebBrowser控件

在上一篇文章中,我们使用WPF WebBrowser控件来创建一个小型Web浏览器。 但是,如该文章所述,与WinForms版本相比,WPF WebBrowser控件有点受限。 关于使用WinForms版本可以轻松完成的事情有很多例子,这些版本要么更难,要么无法用WPF版本实现。

一个小例子是DocumentTitle属性和相应的DocumentTitleChanged事件,这可以轻松获取和更新窗口的标题以匹配当前网页的标题。 我们在的WPF应用程序中用这个理由测试WinForms版本:

<Window x:Class="WpfTutorialSamples.Misc_controls.WindowsFormsHostSample"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
        Title="WindowsFormsHostSample" Height="350" Width="450">
    <Grid>
        <WindowsFormsHost Name="wfhSample">
            <WindowsFormsHost.Child>
                <wf:WebBrowser DocumentTitleChanged="wbWinForms_DocumentTitleChanged" />
            </WindowsFormsHost.Child>
        </WindowsFormsHost>
    </Grid>
</Window>
using System;
using System.Windows;

namespace WpfTutorialSamples.Misc_controls
{
	public partial class WindowsFormsHostSample : Window
	{
		public WindowsFormsHostSample()
		{
			InitializeComponent();
			(wfhSample.Child as System.Windows.Forms.WebBrowser).Navigate("http://www.wpf-tutorial.com");
		}

		private void wbWinForms_DocumentTitleChanged(object sender, EventArgs e)
		{
			this.Title = (sender as System.Windows.Forms.WebBrowser).DocumentTitle;
		}
	}
}

WPF教程之 WindowsFormsHost控件

特别注意我们在窗口添加WinForms命名空间这行,以便我们可以从中引用控件:

xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"

这将允许我们使用wf:前缀引用WinForms控件。

您可以看到,WindowsFormsHost使用起来相当简单。 它有一个Child属性,你可以在其中定义一个WinForms控件,就像WPF Window只保存一个根控件一样。 如果在WindowsFormsHost中需要来自WinForms的更多控件,可以使用WinForms中的Panel控件或任何其他容器控件。

如上所述,WinForms WebBrowser控件使用wf前缀引用System.Windows.Forms程序集。

后台代码中,我们在构造时调用Navigate,在启动时有一个可见的网页而不是空白。 然后我们处理DocumentTitleChanged事件,在该事件中,我们根据WebBrowser控件的当前DocumentTitle值更新Window的Title属性。

恭喜,您现在拥有一个包含WinForms WebBrowser控件的WPF应用程序。

小结

正如您所看到的,在WPF应用程序中使用WinForms控件非常简单,但问题是:这是一个好主意吗?

通常,您可能希望避免它。 有许多问题可能会或可能不会影响您的应用程序(这些MSDN文章中描述了很多问题:http://msdn.microsoft.com/en-us/library/aa970911%28v=VS.100%29.aspx),但更严重的问题是,在.NET框架的未来版本中可能不支持这种UI框架混合。

最后,决定权在你 – 你真的需要WinForms控件吗?还是一个能正常工作的WPF替代?

作者:唐伯虎点蚊香,如若转载,请注明出处:https://www.web176.com/wpf/16034.html

(0)
打赏 支付宝 支付宝 微信 微信
唐伯虎点蚊香的头像唐伯虎点蚊香
上一篇 2023年4月19日
下一篇 2023年4月19日

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注