Windows窗体中的WPF控件?

WPF control in windows forms?(Windows窗体中的WPF控件?)

本文介绍了Windows窗体中的WPF控件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一些可用于 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?

还有其他注意事项吗?

推荐答案

答案:

  1. 是的,有可能.
  2. 是的,您可以在 WPF 中创建它们.
  3. 主要考虑的是,当使用 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.

代理最容易实现如下:

  1. System.Windows.Forms.Control
  2. 派生代理
  3. 在代理的构造函数中:实例化您的 WPF 控件,将其添加到新构造的 HwndSource,并将 HwndSource 添加为代理的子项
  4. 向代理添加属性和方法,只调用真实 WPF 控件的等效属性和方法
  1. Derive the proxy from System.Windows.Forms.Control
  2. In the proxy's constructor: instantiate your WPF control, add it to a newly constructed HwndSource, and add the HwndSource as a child of your proxy
  3. 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 的 Bitmap 或 WPF 的 BitmapSource.如果您有一个通常只支持 RoutedEvents 的 WPF 控件,请添加老式的事件处理程序以方便 WinForms 人群.

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控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Windows窗体中的WPF控件?

基础教程推荐