Integrating WPF in WinForms in VS 2010

Introduction

In this article we will see how we can integrate WPF User control into Winform application in Visual Studio 2010.

Creating Blank Solution

Fire up Visual Studio 2010 and create a Blank Solution, name the solution as WPF.Winform.Integration.

1.gif

Let's add a Winform Application and give it a name "WinformSample". As we are integrating WPF into Winforms so make sure this is your start up Project for the solution.

2.gif

Let's see simplest thing what we can do. We can add two properties of an entity from the Winform to the WPF. So I have designed the following Winform with two text boxes (Name and Contact) and then a Button to add to the UserControl.

3.gif 

To host a WPF User Control, we need a control called "Element Host".

4.gif 

Add one instance of the Element Host into the application. Resize it accordingly.

5.gif 

Now, let's add a WPF Application to the solution, name the project as WPFSample.

6.gif 

Now that we have added the the WPF Application, the following is the solution structure.

7.gif 

Now, the most important part, add the project reference of the WPF Application to the Winforms Application.

8.gif 

The following xaml represents the User Control.

9.gif 

In Winforms design page, if you see the Element Host control, you can find a option fly on the top right corner. Click on that to see the options.

10.gif 

Click on the drop down, and you should see your user control. If you are unable to see the User Control, clean and rebuild your solution one more time.

11.gif 

Select the User Control and it would be added to the Element Host.

12.gif
 
Now that we have added the User Control to the Winforms application. Let's write some code that would reflect from Winform application to WPF User Control.

We have to define a class that would represent our Entity, so let's add a class and name it as Person. 

13.gif 

The following is the class structure for the Entity Person.

14.gif 

Now we should have a method, that can be accessed from Winform applciation. The following method refreshes the ItemsSource property and set it.

15.gif 

Go back to the Winforms Application code behind and on the Button click of Add Button, write the following lines of code.

16.gif 

That's it, lets run the application.
 
17.gif

18.gif 

We are able to communicate from Winforms to WPF User Control.

Hope this article helps.