Monday, August 23, 2010

Mixing WPF and WinForms

One of the earliest—but still important—tenets of software engineering is the concept of reuse with “software building blocks”. In the .NET framework, user controls are the quintessential building blocks, giving you a simple yet powerful way to encapsulate a set of visual components into a more complex one. This holds true both in the WinForms realm and the WPF realm. That is, you can build WinForms user controls and embed them in WinForms applications, and likewise build WPF user controls and embed them in WPF applications. As a designer in at least one of these realms, you likely know this well.
But what is not well known, nor particularly obvious, is that you can build hybrids, embedding WPF controls in a WinForms application or WinForms controls in a WPF application. All you need is a simple adapter when using controls from the opposite realm (Figure 1). I deliberately use the term control in the figure rather than user control because this interoperability is not limited to user controls. You can embed any controls—your custom controls or standard .NET controls—from one technology into the other. This article provides an in-depth look into the symmetries of hybrid applications. As a by-product, the occasional asymmetries become readily apparent. Here is the first one: you can actually embed a broader set of WPF elements into a WinForms application: not just elements that derive from Control, but those that derive from a broader base class called UIElement (see Embedding Standard .NET Components for more on this).
Read more: simple-talk