Host a WPF control into Win32 Windows Form
This article would explain how to host a WPF control into the Windows Form. I would create the WPF Control, and a Windows form application, which would host the WPF control. In the next article we would see how event from WPF control could be passed to hosting
windows form.
Note: In Windows Form we can host only a WPF element, so we would use the Grid element in WPF and put the control(s) into it to make a user control. In this sample I would 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 would 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 would 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 would 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 as
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 would add these by itself.
- WindowsBase
- WindowsFormsIntegration
Compile and Run the Windows Application you would 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 would extend this to explain how to share the data and send the event to host from the WPF control.
轉自【http://www.a2zdotnet.com/View.aspx?Id=78#.Ub8fGZyvy3I】