- WPF and Windows Forms Interoperation
- Hosting Windows Forms Controls in WPF
- Layout Support
- Ambient Properties
- Behavior
- Hosting WPF Controls in Windows Forms
- WPF vs. WinForms
- Сопоставление свойств Windows Forms и WPF Windows Forms and WPF Property Mapping
- Сопоставление свойств с элементом WindowsFormsHost Property Mapping with the WindowsFormsHost Element
- Обновления свойств родительского элемента Updates to Parent Properties
- Сопоставление свойств с элементом управления ElementHost Property Mapping with the ElementHost Control
WPF and Windows Forms Interoperation
WPF and Windows Forms present two different architectures for creating application interfaces. The System.Windows.Forms.Integration namespace provides classes that enable common interoperation scenarios. The two key classes that implement interoperation capabilities are WindowsFormsHost and ElementHost. This topic describes which interoperation scenarios are supported and which scenarios are not supported.
Special consideration is given to the hybrid control scenario. A hybrid control has a control from one technology nested in a control from the other technology. This is also called a nested interoperation. A multilevel hybrid control has more than one level of hybrid control nesting. An example of a multilevel nested interoperation is a Windows Forms control that contains a WPF control, which contains another Windows Forms control. Multilevel hybrid controls are not supported.
Hosting Windows Forms Controls in WPF
The following interoperation scenarios are supported when a WPF control hosts a Windows Forms control:
The WPF control may host one or more Windows Forms controls using XAML.
It may host one or more Windows Forms controls using code.
It may host Windows Forms container controls that contain other Windows Forms controls.
It may host a master/detail form with a WPF master and Windows Forms details.
It may host a master/detail form with a Windows Forms master and WPF details.
It may host one or more ActiveX controls.
It may host one or more composite controls.
It may host hybrid controls using Extensible Application Markup Language (XAML).
It may host hybrid controls using code.
Layout Support
The following list describes the known limitations when the WindowsFormsHost element attempts to integrate its hosted Windows Forms control into the WPF layout system.
In some cases, Windows Forms controls cannot be resized, or can be sized only to specific dimensions. For example, a Windows Forms ComboBox control supports only a single height, which is defined by the control’s font size. In a WPF dynamic layout, which assumes that elements can stretch vertically, a hosted ComboBox control will not stretch as expected.
Windows Forms controls cannot be rotated or skewed. For example, when you rotate your user interface by 90 degrees, hosted Windows Forms controls will maintain their upright position.
In most cases, Windows Forms controls do not support proportional scaling. Although the overall dimensions of the control will scale, child controls and component elements of the control may not resize as expected. This limitation depends on how well each Windows Forms control supports scaling.
In a WPF user interface, you can change the z-order of elements to control overlapping behavior. A hosted Windows Forms control is drawn in a separate HWND, so it is always drawn on top of WPF elements.
Windows Forms controls support autoscaling based on the font size. In a WPF user interface, changing the font size does not resize the entire layout, although individual elements may dynamically resize.
Ambient Properties
Some of the ambient properties of WPF controls have Windows Forms equivalents. These ambient properties are propagated to the hosted Windows Forms controls and exposed as public properties on the WindowsFormsHost control. The WindowsFormsHost control translates each WPF ambient property into its Windows Forms equivalent.
Behavior
The following table describes interoperation behavior.
Behavior | Supported | Not supported |
---|---|---|
Transparency | Windows Forms control rendering supports transparency. The background of the parent WPF control can become the background of hosted Windows Forms controls. | Some Windows Forms controls do not support transparency. For example, the TextBox and ComboBox controls will not be transparent when hosted by WPF. |
Tabbing | Tab order for hosted Windows Forms controls is the same as when those controls are hosted in a Windows Forms-based application. Tabbing from a WPF control to a Windows Forms control with the TAB key and SHIFT+TAB keys works as usual. Windows Forms controls that have a TabStop property value of false do not receive focus when the user tabs through controls. — Each WindowsFormsHost control has a TabIndex value, which determines when that WindowsFormsHost control will receive focus. | Not applicable. |
Navigation with arrow keys | — Navigation with arrow keys in the WindowsFormsHost control is the same as in an ordinary Windows Forms container control: The UP ARROW and LEFT ARROW keys select the previous control, and the DOWN ARROW and RIGHT ARROW keys select the next control. — The UP ARROW and LEFT ARROW keys from the first control that is contained in the WindowsFormsHost control perform the same action as the SHIFT+TAB keyboard shortcut. If there is a focusable WPF control, focus moves outside the WindowsFormsHost control. This behavior differs from the standard ContainerControl behavior in that no wrapping to the last control occurs. If no other focusable WPF control exists, focus returns to the last Windows Forms control in the tab order. — The DOWN ARROW and RIGHT ARROW keys from the last control that is contained in the WindowsFormsHost control perform the same action as the TAB key. If there is a focusable WPF control, focus moves outside the WindowsFormsHost control. This behavior differs from the standard ContainerControl behavior in that no wrapping to the first control occurs. If no other focusable WPF control exists, focus returns to the first Windows Forms control in the tab order. | Not applicable. |
Accelerators | Accelerators work as usual, except where noted in the «Not supported» column. | Duplicate accelerators across technologies do not work like ordinary duplicate accelerators. When an accelerator is duplicated across technologies, with at least one on a Windows Forms control and the other on a WPF control, the Windows Forms control always receives the accelerator. Focus does not toggle between the controls when the duplicate accelerator is pressed. |
Shortcut keys | Shortcut keys work as usual, except where noted in the «Not supported» column. | — Windows Forms shortcut keys that are handled at the preprocessing stage always take precedence over WPF shortcut keys. For example, if you have a ToolStrip control with CTRL+S shortcut keys defined, and there is a WPF command bound to CTRL+S, the ToolStrip control handler is always invoked first, regardless of focus. — Windows Forms shortcut keys that are handled by the KeyDown event are processed last in WPF. You can prevent this behavior by overriding the Windows Forms control’s IsInputKey method or handling the PreviewKeyDown event. Return true from the IsInputKey method, or set the value of the PreviewKeyDownEventArgs.IsInputKey property to true in your PreviewKeyDown event handler. |
AcceptsReturn, AcceptsTab, and other control-specific behavior | Properties that change the default keyboard behavior work as usual, assuming that the Windows Forms control overrides the IsInputKey method to return true . | Windows Forms controls that change default keyboard behavior by handling the KeyDown event are processed last in the host WPF control. Because these controls are processed last, they can produce unexpected behavior. |
Enter and Leave Events | When focus is not going to the containing ElementHost control, the Enter and Leave events are raised as usual when focus changes in a single WindowsFormsHost control. | Enter and Leave events are not raised when the following focus changes occur: — From inside to outside a WindowsFormsHost control. |
Multithreading | All varieties of multithreading are supported. | Both the Windows Forms and WPF technologies assume a single-threaded concurrency model. During debugging, calls to framework objects from other threads will raise an exception to enforce this requirement. |
Security | All interoperation scenarios require full trust. | No interoperation scenarios are allowed in partial trust. |
Accessibility | All accessibility scenarios are supported. Assistive technology products function correctly when they are used for hybrid applications that contain both Windows Forms and WPF controls. | Not applicable. |
Clipboard | All Clipboard operations work as usual. This includes cutting and pasting between Windows Forms and WPF controls. | Not applicable. |
Drag-and-drop feature | All drag-and-drop operations work as usual. This includes operations between Windows Forms and WPF controls. | Not applicable. |
Hosting WPF Controls in Windows Forms
The following interoperation scenarios are supported when a Windows Forms control hosts a WPF control:
Hosting one or more WPF controls using code.
Associating a property sheet with one or more hosted WPF controls.
Hosting one or more WPF pages in a form.
Starting a WPF window.
Hosting a master/detail form with a Windows Forms master and WPF details.
WPF vs. WinForms
In the previous chapter, we talked about what WPF is and a little bit about WinForms. In this chapter, I will try to compare the two, because while they do serve the same purpose, there is a LOT of differences between them. If you have never worked with WinForms before, and especially if WPF is your very first GUI framework, you may skip this chapter, but if you’re interested in the differences then read on.
The single most important difference between WinForms and WPF is the fact that while WinForms is simply a layer on top of the standard Windows controls (e.g. a TextBox), WPF is built from scratch and doesn’t rely on standard Windows controls in almost all situations. This might seem like a subtle difference, but it really isn’t, which you will definitely notice if you have ever worked with a framework that depends on Win32/WinAPI.
A great example of this is a button with an image and text on it. This is not a standard Windows control, so WinForms doesn’t offer you this possibility out of the box. Instead you will have to draw the image yourself, implement your own button that supports images or use a 3rd party control. With WPF, a button can contain anything because it’s essentially a border with content and various states (e.g. untouched, hovered, pressed). The WPF button is «look-less», as are most other WPF controls, which means that it can contain a range of other controls inside of it. You want a button with an image and some text? Just put an Image and a TextBlock control inside of the button and you’re done! You simply don’t get this kind of flexibility out of the standard WinForms controls, which is why there’s a big market for rather simple implementations of controls like buttons with images and so on.
The drawback to this flexibility is that sometimes you will have to work harder to achieve something that was very easy with WinForms, because it was created for just the scenario you need it for. At least that’s how it feels in the beginning, where you find yourself creating templates to make a ListView with an image and some nicely aligned text, something that the WinForms ListViewItem does in a single line of code.
This was just one difference, but as you work with WPF, you will realize that it is in fact the underlying reason for many of the other differences — WPF is simply just doing things in its own way, for better and for worse. You’re no longer constrained to doing things the Windows way, but to get this kind of flexibility, you pay with a little more work when you’re really just looking to do things the Windows way.
The following is a completely subjective list of the key advantages for WPF and WinForms. It should give you a better idea of what you’re going into.
Сопоставление свойств Windows Forms и WPF Windows Forms and WPF Property Mapping
Windows Forms и WPF WPF технологии имеют две аналогичные, но разные модели свойств. The Windows Forms and WPF WPF technologies have two similar but different property models. Сопоставление свойств поддерживает взаимодействие между двумя архитектурами и предоставляет следующие возможности: Property mapping supports interoperation between the two architectures and provides the following capabilities:
Позволяет легко сопоставлять соответствующие изменения свойств в среде размещения с размещаемым элементом управления или элементом. Makes it easy to map relevant property changes in the host environment to the hosted control or element.
Обеспечивает обработку по умолчанию для сопоставления наиболее часто используемых свойств. Provides default handling for mapping the most commonly used properties.
Позволяет легко удалять, переопределять или расширять свойства по умолчанию. Allows easy removal, overriding, or extending of default properties.
Гарантирует, что изменения значений свойств на узле автоматически обнаруживаются и преобразуются в размещенный элемент управления или элемент. Ensures that property value changes on the host are automatically detected and translated to the hosted control or element.
События изменения свойства не распространяются на элемент управления размещения или иерархию элементов. Property-change events are not propagated up the hosting control or element hierarchy. Перевод свойства не выполняется, если локальное значение свойства не меняется из-за прямого задания, стилей, наследования, привязки данных или других механизмов, изменяющих значение свойства. Property translation is not performed if the local value of a property does not change because of direct setting, styles, inheritance, data binding, or other mechanisms that change the value of the property.
Используйте PropertyMap свойство WindowsFormsHost элемента и PropertyMap свойство ElementHost элемента управления для доступа к сопоставлению свойств. Use the PropertyMap property on the WindowsFormsHost element and the PropertyMap property on ElementHost control to access property mapping.
Сопоставление свойств с элементом WindowsFormsHost Property Mapping with the WindowsFormsHost Element
WindowsFormsHostЭлемент преобразует свойства по умолчанию WPF WPF в их Windows Forms эквиваленты с помощью следующей таблицы преобразования. The WindowsFormsHost element translates default WPF WPF properties to their Windows Forms equivalents using the following translation table.
Размещение Windows Presentation Foundation Windows Presentation Foundation hosting | Windows Forms Windows Forms | Поведение взаимодействия Interoperation behavior |
---|---|---|
Background (System.Drawing.Color) (System.Drawing.Color) | WindowsFormsHostЭлемент задает BackColor свойство размещенного элемента управления и BackgroundImage свойство размещенного элемента управления. The WindowsFormsHost element sets the BackColor property of the hosted control and the BackgroundImage property of the hosted control. Сопоставление выполняется с помощью следующих правил. Mapping is performed by using the following rules: — Если Background является сплошным цветом, он преобразуется и используется для задания BackColor свойства размещаемого элемента управления. — If Background is a solid color, it is converted and used to set the BackColor property of the hosted control. BackColorСвойство не задано для размещенного элемента управления, поскольку размещаемый элемент управления может наследовать значение BackColor Свойства. The BackColor property is not set on the hosted control, because the hosted control can inherit the value of the BackColor property. Примечание. Размещенный элемент управления не поддерживает прозрачность. Note: The hosted control does not support transparency. Любой цвет, назначенный BackColor , должен быть полностью непрозрачным с альфа-значением 0xFF. Any color assigned to BackColor must be fully opaque, with an alpha value of 0xFF. — Если не Background является сплошным цветом, WindowsFormsHost элемент управления создает точечный рисунок из Background Свойства. — If Background is not a solid color, the WindowsFormsHost control creates a bitmap from the Background property. WindowsFormsHostЭлемент управления присваивает это изображение BackgroundImage свойству размещаемого элемента управления. The WindowsFormsHost control assigns this bitmap to the BackgroundImage property of the hosted control. Это дает эффект, аналогичный прозрачности. This provides an effect which is similar to transparency. Примечание. Это поведение можно переопределить, или можно удалить Background сопоставление свойства. Note: You can override this behavior or you can remove the Background property mapping. | |
Cursor | Cursor | Если сопоставление по умолчанию не было переназначено, WindowsFormsHost Управление проходит по иерархии предков до тех пор, пока не найдет предка с Cursor установленным свойством. If the default mapping has not been reassigned, WindowsFormsHost control traverses its ancestor hierarchy until it finds an ancestor with its Cursor property set. Это значение преобразуется в ближайшее соответствующее Windows Forms курсоре. This value is translated to the closest corresponding Windows Forms cursor. Если сопоставление по умолчанию для ForceCursor свойства не было переназначено, обход для первого предка останавливается с параметром ForceCursor true . If the default mapping for the ForceCursor property has not been reassigned, the traversal stops on the first ancestor with ForceCursor set to true . |
FlowDirection (System.Windows.Forms.RightToLeft) (System.Windows.Forms.RightToLeft) | LeftToRight сопоставляется с No. LeftToRight maps to No. Inherit не сопоставлен. Inherit is not mapped. FlowDirection.RightToLeft сопоставляется с RightToLeft.Yes. FlowDirection.RightToLeft maps to RightToLeft.Yes. | |
FontStyle | Style для размещенного элемента управления System.Drawing.Font Style on the hosted control’s System.Drawing.Font | Набор WPF WPF свойств преобразуется в соответствующий объект Font . The set of WPF WPF properties is translated into a corresponding Font. При изменении одного из этих свойств Font создается новое. When one of these properties changes, a new Font is created. Для Normal : Italic отключено. For Normal: Italic is disabled. Для Italic или Oblique : Italic включен. For Italic or Oblique: Italic is enabled. |
FontWeight | Style для размещенного элемента управления System.Drawing.Font Style on the hosted control’s System.Drawing.Font | Набор WPF WPF свойств преобразуется в соответствующий объект Font . The set of WPF WPF properties is translated into a corresponding Font. При изменении одного из этих свойств Font создается новое. When one of these properties changes, a new Font is created. Для Black , Bold , DemiBold , ExtraBold , Heavy , Medium , SemiBold или UltraBold : Bold включено. For Black, Bold, DemiBold, ExtraBold, Heavy, Medium, SemiBold, or UltraBold: Bold is enabled. Для ExtraLight , Light , Normal , Regular , Thin или UltraLight : Bold отключено. For ExtraLight, Light, Normal, Regular, Thin, or UltraLight: Bold is disabled. |
FontFamily (System.Drawing.Font) (System.Drawing.Font) | Набор WPF WPF свойств преобразуется в соответствующий объект Font . The set of WPF WPF properties is translated into a corresponding Font. При изменении одного из этих свойств Font создается новое. When one of these properties changes, a new Font is created. Размер размещаемого элемента управления Windows Forms изменяется в зависимости от размера шрифта. The hosted Windows Forms control resizes based on the font size. Размер шрифта в WPF WPF выражается в виде одной девяноста-шестой дюйма, а в Windows Forms Севенти дюйма. Font size in WPF WPF is expressed as one ninety-sixth of an inch, and in Windows Forms as one seventy-second of an inch. Соответствующее преобразование: The corresponding conversion is: Windows Forms размер шрифта = WPF WPF Размер шрифта * 72,0/96,0. Windows Forms font size = WPF WPF font size * 72.0 / 96.0. | |
Foreground (System.Drawing.Color) (System.Drawing.Color) | ForegroundСопоставление свойств выполняется с помощью следующих правил. The Foreground property mapping is performed by using the following rules: Если Foreground параметр имеет значение SolidColorBrush , используется Color для ForeColor . — If Foreground is a SolidColorBrush, use Color for ForeColor. | |
IsEnabled | Enabled | Если IsEnabled задано, WindowsFormsHost элемент задает Enabled свойство размещаемого элемента управления. When IsEnabled is set, WindowsFormsHost element sets the Enabled property on the hosted control. |
Padding | Padding | Всем четырем значениям Padding Свойства на размещенном элементе управления Windows Forms присваивается одно и то же Thickness значение. All four values of the Padding property on the hosted Windows Forms control are set to the same Thickness value. -Значения больше MaxValue имеют значение MaxValue . — Values greater than MaxValue are set to MaxValue. |
Visibility | Visible | — Visibleсопоставляется с Visible = true . — Visible maps to Visible = true . Размещенный элемент управления Windows Forms является видимым. The hosted Windows Forms control is visible. Явное присвоение Visible свойству размещенного элемента управления значение не false рекомендуется. Explicitly setting the Visible property on the hosted control to false is not recommended. — Collapsedсопоставляется с Visible = true или false . — Collapsed maps to Visible = true or false . Размещенный элемент управления Windows Forms не рисуется, и его область сворачивается. The hosted Windows Forms control is not drawn, and its area is collapsed. — Hidden : Размещенный элемент управления Windows Forms занимает место в макете, но не является видимым. — Hidden : The hosted Windows Forms control occupies space in the layout, but is not visible. В этом случае Visible свойство имеет значение true . In this case, the Visible property is set to true . Явное присвоение Visible свойству размещенного элемента управления значение не false рекомендуется. Explicitly setting the Visible property on the hosted control to false is not recommended. |
Вложенные свойства элементов контейнера полностью поддерживаются WindowsFormsHost элементом. Attached properties on container elements are fully supported by the WindowsFormsHost element.
Обновления свойств родительского элемента Updates to Parent Properties
Изменения большинства родительских свойств приводят к размещению уведомлений в размещаемом дочернем элементе управления. Changes to most parent properties cause notifications to the hosted child control. В следующем списке описываются свойства, которые не вызывают уведомления при изменении их значений. The following list describes properties which do not cause notifications when their values change.
Например, если изменить значение Background свойства WindowsFormsHost элемента, BackColor свойство размещенного элемента управления не изменится. For example, if you change the value of the Background property of the WindowsFormsHost element, the BackColor property of the hosted control does not change.
Сопоставление свойств с элементом управления ElementHost Property Mapping with the ElementHost Control
Следующие свойства предоставляют встроенные уведомления об изменениях. The following properties provide built-in change notification. Не вызывайте OnPropertyChanged метод при сопоставлении этих свойств: Do not call the OnPropertyChanged method when you are mapping these properties: