Windows Presentation foundation or WPF provides a rich set of GUI components that are hardware accelerated. Still there comes a time when you are required to put a Windows Form Control into your WPF application. Of course you do not want to re-program your user control just because the technology is changing. By not re-programming it means that you are saving your time and investments you have done on creating a Windows Form control.
I myself faced this problem when I was instructed to include a Webcam control which was purely a Windows form user control. Any ways here's the code:
private void LoadWFUserControl()
{
System.Windows.Forms.Integration.WindowsFormsHost host =
new System.Windows.Forms.Integration.WindowsFormsHost();
MyWebcam uc_webcam = new MyWebcam();
host.Child = uc_webcam;
this.grid1.Children.Add(host);
}
VICE-VERSA
The other way round is also possible i.e. HOSTING A WPF CONTROL IN WINDOWS FORMS APPLICATION.
Follow these steps:
- Make a WPF user control DLL (say for example MyControl.dll)
- Add reference of this DLL to your Windows Form Application.
- Add reference of following to your project (required for WPF)
- PresentationCore
- PresentationFramework
- System.Xaml
- WindowsBase
- WindowsFormsIntegration
Example:
void LoadAPFControl()
{
System.Windows.Controls.TextBox wpfTextBox =
new System.Windows.Controls.TextBox();
wpfTextBox.Name = "txName";
wpfTextBox.Text = "WPF TextBox";
wpfTextBox.TextChanged +=
new TextChangedEventHandler(textbox_TextChanged);
ElementHost elementHost = new ElementHost();
elementHost.Dock = DockStyle.None;
elementHost.Width = 150;
elementHost.Height = 50;
elementHost.Child = wpfTextBox;
containerPanel.Controls.Add(elementHost);
}