问题描述
我想创建一些使用WPF和Windows窗体工作的自定义UI控件。
I would like to create some custom UI controls that work with both WPF and Windows Forms.
这可能吗?
如果是这样,我就可以在WPF中创建这些控件或者我需要加时赛使用Windows窗体控件?
If so, can I create these controls in WPF or do I need ot use a Windows Forms control?
是否还有其他方面的考虑?
Are there any other considerations?
推荐答案
回答:
- 是的,这是可能的。
- 是的,你可以在WPF中创建它们。
- 的主要考虑是,利用的WinForms WPF控件时,它需要被包裹在一个
HwndSource
。
如果你正在编写一个控件库,它通常是最好的实现在WPF控件(因为它是如此比的WinForms强大得多),然后创建一个代理,它允许它容易在WinForms的使用。
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.
代理是最容易实现的:
- 源于
System.Windows.Forms.Control的
代理 - 在代理的构造函数:实例化WPF控件,将其添加到新建的
HwndSource
,并添加HwndSource
作为代理的子 - 添加属性和方法,简单地调用等效性和真正的WPF控件的方法代理
- Derive the proxy from
System.Windows.Forms.Control
- In the proxy's constructor: instantiate your WPF control, add it to a newly constructed
HwndSource
, and add theHwndSource
as a child of your proxy - Add properties and methods to the proxy that simply call the equivalent properties and methods of the real WPF control
另外,您可以选择不创建一个代理,而是直接告诉你的WinForms的用户,他们需要把你的控制时,他们将其添加到它们的形式一个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位图或WPF的的BitmapSource。如果你有一个WPF控件的WinForms的人群的舒适性和便利性,将通常只支持RoutedEvents,加上老式的事件处理程序。
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. 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.
这篇关于在Windows窗体中的WPF控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!