Robert Oschler
Robert Oschler

Reputation: 14375

Make WinForms UserControl appear in Toolbox for WPF Visual C# project?

I have a Visual Studio 2012 C# app that uses a WinForms UserControl nested in a WPF WindowsFormsHost container. The app works fine. To add the WinForms UserControl to the project I had to directly edit the main form's XAML file. That wasn't hard but if it's possible I'd like to be able to work from the Toolbox instead.

I found several different threads on Stack Overflow that dealt with problems getting a control to appear in the Visual Studio Toolbox, but none of them discussed getting a WinForms control to appear in the Toolbox of a WPF project (mixed project). Note, the WinForms UserControl does appear in the Toolbox when I use it in a WinForms project. But if the host project is a WPF project, I only see WPF controls in the Toolbox. I tried adding the WinForms control by doing the following:

The contained controls are imported into the .NET Framework Components list but do not show up in the Toolbox after I exit out of the Choose Items dialog. What's odd is, I tried unloading the DLL's controls and repeating this operation a few times and I got inconsistent results. I never got the controls to show, but one time I got a dialog box saying "the controls had been imported but were not active in the Designer" and that I should make sure they are compatible. Another time I got an error box saying the DLL did not contain any usable controls. Most times it would show the imported controls in the .NET Framework Components list with a check mark next to them in the list and the row(s) highlighted in blue. But again, despite not seeing any error or warning messages, they were not shown in the Toolbox. Note, the .NET project that is the source of the WinForms control DLL is a project in the Solution.

So, is it possible to get a Winforms UserControl to show in the Toolbox of a WPF project? If so, how?

Upvotes: 2

Views: 2332

Answers (1)

e_ne
e_ne

Reputation: 8459

Not the most straightforward solution, but you could create a wrapper containing a WindowsFormsHost object. I can't document it, but I suppose that you can't natively combine the two control types because of the airspace problem.

EDIT: I've created a WPF Application solution, then added a WPF User Control Library project to the solution. Afterwards, I've referenced WindowsFormsIntegration in the latter project, added a WindowsFormsHost container, set a System.Windows.Forms.TextBox as its child. After compiling it, in the ToolBox there was a new element, containing the newly created control. I can drag it from there to "All WPF Controls" or select the compiled assembly from the Choose Items dialog.

Upvotes: 1

Related Questions