Windows Presentation Foundation (WPF) and Windows forms are two different mature architectures for creating Windows application interfaces. While Winforms is a time tested, developer-community approved platform, WPF is a next-generation presentation system for building Windows client applications.
Amidst all the `WPF vs Winforms’ talks, what is not well known, 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 .
The two key classes that implement inter-operation capabilities are WindowsFormsHost and ElementHost.
So When is Hybrid Application Practical?
- Huge investment has gone into building custom control libraries
- Reuse controls during migration of application from one technology to another.
- To bring the richness of WPF technology into existing Windows applications.
- Non-availability of certain controls
Usage of ElementHost and WindowsFormsHost
How to get a Winform control working within a WPF application?
In order to use a Winforms UserControl/CustomControl within a WPF application host, the following steps must be taken:
- Reference the WindowsFormsIntegration.dll (should be in the GAC)
- Reference the actual Winforms Control Library projects
- Within the Window that is hosting the Winforms Control add a Winforms Interop container [WindowsFormsHost] and set the Child Property to host the actual WinFormsControlLibrary/CustomControl and example is as follows:
Screenshot of Winforms User Control now running inside WPF window.
How to get a WPF control working within a Winforms application?
In order use a WPF Control within a Winforms application host, the following steps must be taken:
- Reference the WindowsFormsIntegration.dll (should be in the GAC)
- Reference the actual WPF Control Library projects.
- Within the Window/Page that is hosting the Control add a WPF interop container [ElementHost] and set the Child Property to host the actual WpfControlLibrary/UserControl, and example is as follows:
Here is a screenshot of Windows application hosting a WPF Control.
You should by now have understood the fundamentals of WPF and Winforms interoperability. Also, remember that you may encounter rendering issues with more complicated controls but it is always important to be aware of the fact that as a Windows application developer, you can let Winforms and WPF controls coexist.