Windows forms Integration in WPF
Hosting Windows form control in WPF:
Windows Forms to WPF Interop is one of the features of wpf, where the controls existing in winforms can be used in WPF.This is achieved using the windowsformshost.
Namespace: System.Windows.Forms.Integration
Assembly: WindowsFormsIntegration
Below is the sample where a windows forms datatimepicker is used in WPF.
Steps:
1. Create a WPF project HostWindowsControl.
2. Add the following references to the project
a.WindowsFormsIntegration
b.System.Windows.Forms
3. Open the MainWindow.xaml file in designer.
4. Add the window load event
<Window.Resources>
<Window x:Class="HostWindowsControl.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
<Grid Name="Host">
</Grid>
</Window>
<Window.Resources>
5. Open the MainWindow.cs.xaml file, add the following reference.
using System.Windows.Forms;
6. In the window load event add the following code.
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// Createing the interop host control object.
System.Windows.Forms.Integration.WindowsFormsHost hostobject =
new System.Windows.Forms.Integration.WindowsFormsHost();
// Create the DateTimePicker control object.
DateTimePicker DtTime = new DateTimePicker();
// set DateTimePicker control as the hostobject child.
hostobject.Child = DtTime;
// Adding the windows interop host control to the Grid
this.Host.Children.Add(hostobject);
}
7. Now run the application.You will see the DateTimePicker control in the wpf form.