[英]WPF control in windows forms?
I would like to create some custom UI controls that work with both WPF and Windows Forms. 我想创建一些可以同时使用WPF和Windows窗体的自定义UI控件。
Is this possible? 这可能吗?
If so, can I create these controls in WPF or do I need ot use a Windows Forms control? 如果是这样,我可以在WPF中创建这些控件,还是需要使用Windows窗体控件?
Are there any other considerations? 还有其他考虑事项吗?
Answers: 回答:
HwndSource
. 主要考虑因素是,当使用WinForms中的WPF控件时,需要将其包装在HwndSource
。 If you're writing a control library, it is usually best to implement your control in WPF (because it is so much more powerful than WinForms), then create a proxy for it to allow it to easily be used in WinForms. 如果要编写控件库,通常最好在WPF中实现控件(因为它比WinForms强大得多),然后为其创建代理以使其易于在WinForms中使用。
The proxy is most easily implemented as follows: 代理最容易实现,如下所示:
System.Windows.Forms.Control
从System.Windows.Forms.Control
派生代理 HwndSource
, and add the HwndSource
as a child of your proxy 在代理的构造函数中:实例化WPF控件,将其添加到新构造的HwndSource
,并将HwndSource
添加为代理的子级 Alternatively you could choose not to create a proxy, and instead just tell your WinForms users they need to put your control inside a HwndSource when they add it to their Form. 或者,您可以选择不创建代理,而只是告诉WinForms用户,将控件添加到HwndSource时需要将其放入HwndSource中。
Most other issues you will encounter in creating a dual-use control are insignificant or trivial to fix. 创建双重用途控件时遇到的大多数其他问题都是微不足道的或琐碎的。 For example, if you have a feature in your control that accepts images, just design it to accept either WinForms' Bitmap or WPF's BitmapSource. 例如,如果控件中具有接受图像的功能,则只需将其设计为接受WinForms的Bitmap或WPF的BitmapSource。 And if you have a WPF control that would normally only support RoutedEvents, add old-fashioned event handlers for the comfort and convenience of the WinForms crowd. 如果您有一个WPF控件,该控件通常仅支持RoutedEvents,请添加老式事件处理程序,以使WinForms人群感到舒适和方便。
ElementHost
will let you embed a WPF control inside a WinForms form, WindowsFormsHost
let's you insert WinForms controls into a WPF window. ElementHost
允许您将WPF控件嵌入WinForms表单内, WindowsFormsHost
允许您将WinForms控件插入WPF窗口中。
Both are easy to use, and both have minor problems with composition (you can't draw a WPF element over a WinForms element, etc.). 两者都易于使用,并且在组成方面都存在一些小问题(您不能在WinForms元素上绘制WPF元素,等等)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.