TechEd Session: WPF/Windows Forms Hybrid Applications

My second TechEd breakout session was in the Developer tools track (DEV340). This talk covered the interop story between Windows Forms and WPF and showed how to put WPF controls in a Windows Forms application, and Windows Forms controls ina WPF application.

For WPF in a Windows Forms app, it boils down to 4 lines of code:

  • Create an ElementHost control
  • Create the hosted WPF control
  • Add the ElementHost control to a container in the Windows Forms app
  • Set the Child property of the ElementHost to point to the hosted control instance

This looks like the following:

ElementHost host = new ElementHost();
MediaElement mediaEl = new MediaElement();
panel1.Controls.Add(host);
host.Child = mediaEl;

You will also need to add a reference to WindowsFormsIntegration.dll and add a using statement for the System.Windows.Forms.Integration namespace, as well as a reference and using statement for the namespace of the WPF control that you are hosting (System.Windows.Controls in this case for the MediaElement control). You will also likely want to set the Dock property of the host control to Fill its container, and may want to keep the references for the host and the hosted control around in member variables on the form so that you can access them from event handlers and such.

To go the other way, it is the same basic process, but the host control is a WindowsFormsHost instead of ElementHost.

There are also a number of interop challenges you will face, which I covered in the talk, and showed how to overcome some of those challenges through property maps.

Finally, I demonstrated that in VS 2008, you can drag and drop WPF controls onto a Windows Form, and the ElementHost will be added and configured for you (basically it writes those four lines of code for you.

You can download the slides and demos for this session here:SlidesDemos