uppose you've been given the green light to use Windows Presentation Foundation (WPF) in the latest version of your user interface. There's just one snag—not all the third party controls critical to your application have a WPF version. Fortunately, WPF has excellent support for legacy controls; however, you'll need to write some glue code to provide the interoperability.
Hosting a Windows Forms Control in WPF
The key element for hosting legacy controls in WPF is a special control called, appropriately enough, WindowsFormsHost. Here's a walkthrough of the process for adding a Windows Forms TextBox to a WPF window.
First, create a window and, in the XAML, add the following namespaces to the <Window> tag:
Next, add a WindowsFormsHost element to the window:
Now, add a Windows Forms TextBox as a child of the WindowsFormsHost element.
<Forms:TextBox x:Name="txtTextBox" Text="Windows Forms TextBox" />
|Figure 1. WPF Hosting Windows Forms Control: This Windows Forms TextBox control is hosted in a WPF window using the WindowsFormsHost control.
When you run the application, you'll see a window similar to Figure 1.
You could accomplish the same thing in code by setting the Child property of the WindowsFormsHost to a System.Windows.Forms.TextBox, as shown below:
System.Windows.Forms.TextBox textBox =
textBox.Text = "Windows Forms TextBox";
windowsFormsHost1.Child = textBox;
You aren't limited to hosting Windows Forms controls in WPF applications; it's just as easy to go the other direction and host WPF controls in your Windows Forms applications.