Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Enable WPF/Windows Forms Interoperability with WPF Commands

Windows Presentation Foundation (WPF) can interoperate with Windows Forms, letting you add legacy controls to your new interface—or new WPF controls to your existing Windows Forms applications. Either way, you need to make them play nicely together.


advertisement
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.

Author's Note: You can follow this step-by-step guide or download the sample code and study that as you read this article.

First, create a window and, in the XAML, add the following namespaces to the <Window> tag:

xmlns:my="clr-namespace:System.Windows.Forms.Integration; assembly=WindowsFormsIntegration" xmlns:Forms="clr-namespace:System.Windows.Forms; assembly=System.Windows.Forms"

Next, add a WindowsFormsHost element to the window:

<my:WindowsFormsHost Margin="9,11,11,0" Name="windowsFormsHost1" Height="26" VerticalAlignment="Top" />

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 = new System.Windows.Forms.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.



Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap