WPF User Controls in WinForms App

by QuayTech Support for Blog
WPF User Controls in WinForms App
Yes, we really did this!

If you have to maintain a legacy WinForms app, but want to start using WPF components in a legacy application … this is how you can do just that!

 

a bit of background

So, how did we start using WPF components in a legacy application …

Luckily, Microsoft provide an ElementHost class in the System.Windows.Forms.Integration (you will need to add a reference to WindowsFormsIntegration).  The ElementHost class is a WinForms control (System.Windows.Forms.Control) that has a Child property of type UIElement (System.Windows).  This does what we need it to, but if we have a large application which we may be looking to use many WPF controls in, how can we guarantee the ElementHost contains the correct child type?

One solution would be to check the child’s type.

However, this is a run-time check, ideally we want to have a compile-time check to catch these issues early.  Plus this would be something we would have to remember to check each time and that is never a good a thing!  There is a solution.  We make a generic windows form.

Now when we have our variable:

We can be assured that it can only contain our user control ucHelloWorld1.

How to make a Generic Windows Form
  1. Step one is to get the code-behind file and the designer file open.  If we edit the class definition of the code-behind file, the designer file will be treated as a different class and will not show up in the solution explorer.  This can be done by opening the code-behind, right-clicking the call to InitializeComponents() in the constructor and clicking Go to Definition.
  1. Once you have both the files open, add the type parameter to both files.  You will need to have a type constraint to allow the type to be set on your ElementHost class. Something like:

Example Source Code

Code Behind:

Designer File:

Want to know more?

If you would like to read more on using WPF components in a legacy application, or just take some time to do extra reading around WPF take a look at these articles:

MSDN Walkthrough – First WPF Application

MSDN – Hosting WPF Composite Control in Windows Forms

Or, contact me at QuayTech on info@quaytechsystems.co.uk !

Dynamics 365 Training
Prev post Query Data in Dynamics 365 using Web API

We were recently tasked to write a Web API for one of our clients to retrieve…

Dynamics 365 Training
Next post Dynamics 365 Training

WOW, what a day! Following on from application development work we completed on Dynamics 365 for…