Host a WPF control into Win32 Windows Form
This article wocould explain how to host a WPF control into the Windows Form. I wocould create the WPF Control, and a Windows form application, which wocould host the WPF control. in the next article we wocould see how event from WPF control cocould be passed to hosting
Windows form.
Note:In Windows Form we can host only a WPF element, so we wocould use the Grid element in WPF and put the control (s) into it to make a user control. in this sample I wocould use button and text box WPF controls.
Step1. Creating the WPF Control:
- Open Visual Studio 2008.
- Open the project creation template from File-> Create project menu.
- Select the WPF User Control Library.
- Name the project as WpfUserControlLib and create the project.
- It wocould create UserControl1.xaml and UserControl1.xaml. cs
In the project.
- Inherit the usercontrol1 from the grid elemement instead of the usercontrol, as I stated in the note above we can not host a control rather we can host a element into the windows form. this change has to be done in both
Usercontrol1.xaml and usercontrol1.xaml. CS.
- Now drop the lable, text box and two buttons (OK and cancel ).
- Build the wpfusercontrollib.
Make sure WpfUserControlLib contains following references, though Visual Studio 2008 wocould do these by itself
- System
- Presentationcore
- Presentationframework
- Windowsbase
Step 2: creating the Windows Forms Host application in the current solution:
- Open the Project Creation template from file-> Add-> new project menu.
- Select windows form application from the Project template and name it
Winformwpfhostapp.
- From the Toolbox (WPF interoperability tab) Drop the elementhost control to the form1. it wocould be named as elementhost1.
- Set the dock property to fill of elementhost1 control (optional ).
- Add the reference of wpfusercontrollib project created in the step1.
- Create the class level variable of the wpfusercontrol type
WpfUserControlLib.UserControl1 _WPFUserControl = null;
- Add the following code to create the instance of the WPF user control and attach it with element host in the constructor or load event of the form.
elementHost1.Dock = DockStyle.Fill; _WPFUserControl = new WpfUserControlLib.UserControl1(); elementHost1.Child = _WPFUserControl;
- Make sure the form size is good enough to display the WPF control.
Make sure WinFormWPFHostApp contains following references, though Visual Studio 2008 wocould add these by itself.
- Windowsbase
- Windowsformsintegration
Compile and Run the Windows Application you wocould see the WPF control is hosted in the Windows Control.
Summary:We can use the power of the WPF Controls visual elements into the WinForm application by hosting very easily. in the Next Article I wocould extend this to explain how to share the data and send the event to host from the WPF control.
From [http://www.a2zdotnet.com/View.aspx? Id = 78 #. Ub8fGZyvy3I]